Adding manual validation on angular mat form field

2020-05-09 19:06发布

问题:

I am working on a angular application and using mat form fields in it.

My code for mat form field including validation is as follows.

<mat-form-field appearance="fill">
  <mat-label> {{ Email }}</mat-label>
  <input formControlName="email">
  <mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
  <mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}</mat-error>
</mat-form-field>

Now in TS file I have a flag, let's say

    duplicateField = true

Now when this flag is true I want to show my own error message on mat form field and if this field is false I want my other validations to work as before. How can i do that?

回答1:

You can do:

<mat-form-field appearance="fill">
  <mat-label> {{ Email }}</mat-label>
  <input formControlName="email">

  <div *ngIf="duplicateField; then customMessage else otherMessages"></div>

  <ng-template #customMessage>
     <mat-error>My custom message</mat-error>
  </ng-template>

  <ng-template #otherMessages>
     <mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
     <mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}</mat-error>
  </ng-template>
</mat-form-field>


回答2:

HTML

<mat-form-field appearance="fill">
  <mat-label> {{ Email }}</mat-label>
  <input formControlName="email">
  <mat-error>{{getErrorMessage()}}</mat-error>
</mat-form-field>

TS

this.YOURFORMGROUPNAME= this.formBuilder.group({
      email: ['', [Validators.required, Validators.minLength(12)]]
    });

getErrorMessage() {
    const emailFormControl = this.YOURFORMGROUPNAME.get('email');

    if (emailFormControl.hasError('required')) {
      return 'Email is required.';
    }

    if (emailFormControl.value.toString().length !== 12) {
        emailFormControl.setErrors({
            'errorLength': true
        });
    }

    if (emailFormControl.hasError('errorLength')) {
        return 'Value can be 12 characters long.';
    }
  }