mat-error doesn't show that it is an error message?

Viewed 50
ts
formControl = new FormControl('', [
    Validators.required, Validators.pattern(/^[a-zA-Z_-]$/),
    Validators.minLength(5), Validators.maxLength(32)
  ]);

  errorMessage(): any {
    if (this.formControl.hasError('required')) {
      return 'You must enter a value';
    } else if (this.formControl.hasError('pattern')) {
      return 'Username can only be letters,underscores and horizontal lines';
    }
  }
html
<mat-error>{{errorMessage()}}</mat-error>
  1. this.formControl.hasError('required') It's works
  2. this.formControl.hasError('pattern') It isn't works

I checked the angular-material document, but did not find the usage. Why does it produce such a result?

1 Answers

The problem is with the pattern you have provided. The correct pattern would be /^[a-zA-Z_-]{5,32}$/. Note the length in the pattern.

You formControl code would be following:

  formControl = new FormControl('', [
    Validators.required, 
    Validators.pattern(/^[a-zA-Z_-]{5,32}$/),
    Validators.minLength(5), 
    Validators.maxLength(32)
  ]);

And you should also put a condition on mat-error so that it is only rendered when the control is invalid. Like this:

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

Link to Stackblitz Demo.

Related