for example I have an input , and I add muti validate conditions like: required , mail and pattern , so any one failed will lead the controls.status gave me "INVALID" , what shall I do if I want to know which one is failed?
How do you determine which validator condition failed in angular 8
Asked Answered
are you using template driven forms or reactive forms? –
Caraway
write in .html {{control?.errors|json}} and you will see the errors –
Cyanotype
To display errors when using template driven forms:
<input type="text"
id="name"
required
[(ngModel)]="model.name"
name="name"
#name="ngModel">
<div>{{name.errors | json}}</div>
To display errors when using reactive forms:
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<div>{{profileForm.get('firstName').errors | json}}</div>
</form>
I suggest to use or create some directive/component which will display errors for you.
if you use reactive forms , hasError Function to check validators type , this is a example:
<input matInput placeholder="First Name" autocomplete="off" [formControl]="firstName" name="fname" required>
<mat-error *ngIf="firstName.hasError('required')">
First Name is required.
</mat-error>
<mat-error *ngIf="firstName.hasError('minlength')">
First Name is too short.
</mat-error>
<mat-error *ngIf="firstName.hasError('maxlength')">
First Name is too long.
</mat-error>
© 2022 - 2024 — McMap. All rights reserved.