Reputation: 1927
I'm having an angular reactive form with validators (taken from the scheme, but refer to it as required). The control is invlid when the form is initiate, while it is still pristine, not touched and not dirty. Is there any assumption why it happens\how to avoid it ?
Upvotes: 4
Views: 5021
Reputation: 10541
All required Form control which marked as required like below in a form
createFormGroup() {
return new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
mobile: new FormControl('', [Validators.required]),
country: new FormControl('', [Validators.required])
});
}
so above form control email, mobile and country will be invalid, so that user will disable submit button or show some message to the user
So here you can display when User touched field like below
<input formControlName="mobile">
<span *ngIf="mobile.invalid && mobile.errors.required">
Mobile is required.
</span>
<span *ngIf="mobile.invalid && mobile.errors.invalidNumber">
Value has to be a number.
</span>
Hope this will help.
Upvotes: 0
Reputation: 57981
use, e.g.
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
...
</div>
from the official docs
Why check dirty and touched? You may not want your application to display errors before the user has a chance to edit the form. The checks for dirty and touched prevent errors from showing until the user does one of two things: changes the value, turning the control dirty; or blurs the form control element, setting the control to touched.
Upvotes: 1