multiple mat-error for formArray unable to figureout

2.5k views Asked by At

I want to have multiple error messages and unable to figure out how to do so..? Here I need to validate each step separately so that's why I am using this stepper

<form [formGroup]="formGroup" method="POST" #f="ngForm">
    <mat-vertical-stepper #linearVerticalStepper="matVerticalStepper" formArrayName="formArray" [linear]="true">
        <mat-step formGroupName="0" [stepControl]="formArray?.get([0])">
            <mat-form-field>
               <mat-label>Email</mat-label>
               <input matInput formControlName="emailCtrl" required>
               <mat-error>This field is required</mat-error>
               <mat-error>Invalid Email</mat-error>
            </mat-form-field>
        </mat-step>
   </mat-vertical-stepper>
</form>

and form builder is:-

ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          emailCtrl: [
            "",[
            Validators.required,     

//This field is required

            Validators.pattern(
              "^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$" 

// Invalid Email Provided

            )]
          ],
        }),
      ])
    });
  }
2

There are 2 answers

2
AudioBubble On BEST ANSWER

The reason you can't have both validation message showing is because of the source code itself.

If you open the source code on their official repository, on the right line, you will see that the email validator doesn't pop an error for empty values.

If you wish to display both errors, you will have to overwrite the validator yourself and provide it to your own form control.

If you don't know how to do it, you have the documentation about custom validators to help you.

0
S Wizard On

I knwo it's too late. But i think it will be helpful for future refrences. It's in their official example .If you take a close look on their email validation error message it will be like this.

 <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error

and in in ts file you have to define the messages which you want to show accroding to the error

getErrorMessage() {
if (this.email.hasError('required')) {
  return 'You must enter a value';
}

return this.email.hasError('email') ? 'Not a valid email' : '';
  }