Reputation: 673
I have angular 11 template driven form with this input
<form #currentForm="ngForm">
<input matInput type="number" min="18" placeholder="Your age" name="age" [(ngModel)]="memberDetailForm.age">
</form>
{{ currentForm.controls.age?.errors | json }}
{{ currentForm.valid }}
Here form is not performing min validation check, even if I enter 15 which is less than 18, I see no errors and form shows valid. However if I change the input type to text and have some other check like minLenth="5" and enter 4 chars, the error shows up and forms become invalid.
Can anybody help me understand this strange behavior?
Upvotes: 0
Views: 1682
Reputation: 7821
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:
ngZone
from throwing a navigation-related warning unnecessarily (#25839)HttpClient
supports specifying request metadata (#25751)min
and max
Forms validators added (#39063)APP_INITIALIZER
work with observables (#33222)Upvotes: 1