Another common scenario when working with forms is the need to validate the inputs to ensure the correct data is submitted.
In this activity, you'll learn how to validate forms with reactive forms.
-
Import Validators
Angular provides a set of validation tools. To use them, first update the component to import
Validators
from@angular/forms
.import {ReactiveFormsModule, Validators} from '@angular/forms';@Component({...})export class AppComponent {}
-
Add validation to form
Every
FormControl
can be passed theValidators
you want to use for validating theFormControl
values. For example, if you want to make thename
field inprofileForm
required then useValidators.required
. For theemail
field in our Angular form, we want to ensure it's not left empty and follows a valid email address structure. We can achieve this by combining theValidators.required
andValidators.email
validators in an array. Update thename
andemail
FormControl
:profileForm = new FormGroup({ name: new FormControl('', Validators.required), email: new FormControl('', [Validators.required, Validators.email]),});
-
Check form validation in template
To determine if a form is valid, the
FormGroup
class has avalid
property. You can use this property to dynamically bind attributes. Update the submitbutton
to be enabled based on the validity of the form.<button type="submit" [disabled]="!profileForm.valid">Submit</button>
You now know the basics around how validation works with reactive forms.
Great job learning these core concepts of working with forms in Angular. If you want to learn more, be sure to refer to the Angular forms documentation.