user1059939
user1059939

Reputation: 1715

How do I force the display of validation errors?

I have a pretty standard Material Form and everything is sweet.

When I submit my form, I optionally get validation errors, I loop through these matching the key to the control, then set the validation error. Like this with the loop removed.

I don't really think it matters, but here is the relevant part.

 const control = this.form.get(key);
 if (control) {
     control.setErrors({
         server: response.validationErrors[key]
     },{
         emitEvent: true
     });

     // I was trying things like
     // control.markAsTouched() but it did nothing
 }

At this point, my form is displaying Red Fields which is great.

shows red fields

But it doesn't show the error message until I interact with the field, which is an annoyance.

shows red fields after interaction displaying the error

However, the thing that might be causing this, is that I am not using <form (submit)="onSubmit(model)"> syntax. Therefor on my buttons i am not using type=submit and attr.form="my-form"

So at no point is the form traditionally submitted. I believe this may be an issue here.

If I read the material Form Field Docs. It tells me:

Error messages can be shown under the form field underline by adding mat-error elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted.

Notice that last line? I find it hard to properly understand it.

Question:

Is there a mechanism that allows me to force the display of these validation errors straight away without the interaction?

Upvotes: 0

Views: 2582

Answers (1)

Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

check out this StackBlitz link

here is your html template file... [errorStateMatcher]="matcher" is important.

<form class="example-form">
    <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
       [errorStateMatcher]="matcher">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
          Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
          Email is <strong>required</strong>
    </mat-error>
   </mat-form-field>
 </form>

and in your ErroStateMatcher class file..

export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
     const isSubmitted = form && form.submitted;
      return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
      } 
}

Upvotes: 0

Related Questions