首页 > 解决方案 > 不同验证器的两个 mat-error

问题描述

我有一个反应形式,我在其中添加位置并需要名称、状态、纬度和经度字段。我已经对纬度和经度使用了自定义模式验证,并使用它们来显示错误消息,如下所示 -

<mat-form-field appearance="standard" style="display: block;">
            <mat-label>Latitude</mat-label>
            <input formControlName="lat" matInput placeholder="Enter Latitude">
            <mat-icon matSuffix>location_on</mat-icon>
            <mat-hint>Mandatory Field</mat-hint>
            <mat-error *ngIf="editLocationForm.controls.lat.errors?.required && editLocationForm.controls.lat.dirty">
              Latitude is Required</mat-error>
            <mat-error *ngIf="editLocationForm.controls.lat.errors?.pattern && editLocationForm.controls.lat.touched">
              Latitude should be in correct format</mat-error>
          </mat-form-field>

只要条件成立,我就可以看到这两个错误消息。我正在尝试使用必需和 MinLength 验证器对我的城市名称执行相同的操作,如下所示-

<mat-form-field appearance="standard" style="display: block;">
            <mat-label>Location Name</mat-label>
            <input matInput formControlName="name" placeholder="Enter City Name">
            <mat-icon matSuffix>location_on</mat-icon>
            <mat-hint>Mandatory Field</mat-hint>
            <mat-error *ngIf="editLocationForm.controls.name.errors?.required && editLocationForm.controls.name.dirty">
              Location Name is Required</mat-error>
            <mat-error
              *ngIf="editLocationForm.controls.name.errors?.minLength && editLocationForm.controls.name.touched">
              Location Name should have min. 4 characters</mat-error>
          </mat-form-field>

我的表单字段变红,但当名称少于 4 个字符时我看不到错误消息。这是我初始化表单的方式 -

this.editLocationForm = this.formBuilder.group(
      {
        id: [''],
        name: ['', [Validators.required, Validators.minLength(4)]],
        status: ['', Validators.required],
        lat: ['', [Validators.required, Validators.pattern(/^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/)]],
        lon: ['', [Validators.required, Validators.pattern(/^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/)]]
      }
    )

为什么我看不到城市名称的错误消息?

标签: angularangular-materialangular-reactive-forms

解决方案


editLocationForm.controls.name.errors?.minLength应该写为 *editLocationForm.controls.name.errors?。minlength带有一个小“L”。

才知道这件事。


推荐阅读