Displaying the Validation/Error messages
We need to provide a short and meaningful error message to the user.
Angular creates a FormControl
for each and every field, which has ngModel
directive applied. The FormControl
exposes the state of form elements like valid, dirty, touched, etc.
There are two ways in which you can get the reference to the FormControl
.
One way is to use the currentForm
variable. We can use the currentForm.controls.age.valid
to find out if the age
is valid.
The other way is to create a new local variable for each FormControl
For Example, the following age="ngModel"
creates the age
variable with the FormControl
instance.
<input type="text" id="age" name="age" required minlength="10"
#age="ngModel" [(ngModel)]="contact.age">
Now, we have a reference to the age
FormControl instance, we can check its status. We use the valid
property to check if the age
has any errors.
valid
: returns either invalid status or null which means a valid status
<div *ngIf="!age?.valid && (age?.dirty || age?.touched)">
Invalid Age Or Required
</div>
For Complete Sample check here.
To apply min/max validation on a number you will need to create a Custom Validator
Check this Answer to see the Implementation.
Update:
Angular v12 is now available & Support From the Community
The Angular community has been hard at work improving the Angular experience for everyone by contributing to the framework — thank you!
Here are some of the PRs that have been landed thanks to your incredible work:
- Avoid
ngZone
from throwing a navigation-related warning unnecessarily (#25839)
HttpClient
supports specifying request metadata (#25751)
min
and max
Forms validators added (#39063)
- Support
APP_INITIALIZER
work with observables (#33222)