How do you determine which validator condition failed in angular 8
Asked Answered
U

2

6

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?

Untread answered 26/6, 2019 at 9:44 Comment(2)
are you using template driven forms or reactive forms?Caraway
write in .html {{control?.errors|json}} and you will see the errorsCyanotype
C
11

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.

Caraway answered 26/6, 2019 at 9:55 Comment(0)
C
8

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>
Clemons answered 26/6, 2019 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.