Rahul Uttarkar
Rahul Uttarkar

Reputation: 3627

Displaying multiple 'mat-error' validation in template driven form

How to display single error correctly on validating multiple errors using ng if else in template driven form.

<form>
    <mat-card>
               <mat-card-content>
            <mat-form-field>
            
                <input id="email" name="email" #ref_email="ngModel" matInput type="email" email placeholder="Email" [(ngModel)]="email" required>
                
                <mat-error *ngIf="!ref_email.valid && ref_email.errors.required">
                    Email is required
                </mat-error>
                
                <mat-error *ngIf="!ref_email.valid && ref_email.errors.email">
                    Email is not valid
                </mat-error>
                
            </mat-form-field>
        </mat-card-content>        
    </mat-card>
</form>

enter image description here

Upvotes: 5

Views: 6947

Answers (1)

MarcoLe
MarcoLe

Reputation: 2499

First of all even on template driven forms you need to reference your form with a html property something like this: <form #userForm="ngForm">
After that you can check to the errors of the referenced form:

                <mat-error *ngIf="userForm.controls['email']?.errors?.required">
                    Email is required.
                </mat-error>

                <mat-error *ngIf="userForm.controls['email']?.errors?.email">
                    Email is not valid.
                </mat-error>

Upvotes: 4

Related Questions