如何区分多个Validators.pattern

时间:2018-02-17 16:41:28

标签: angular validation angular-validation

我有一个输入,用户需要输入经度。我希望能够在用户键入NaNNot-Precise-Enough值时显示不同的错误消息。我正在使用FormControl.hasError('ValidatorsName')通过验证来获取错误,但似乎无法区分这些模式。

模板:

<mat-form-field class="form-field">
    <input matInput placeholder="Logitude" [formControl]="longitude">
    <mat-error *ngIf="longitude.hasError('pattern')">
        Longitude must be <strong>a number</strong>
    </mat-error>
    <!-- I want to be able to check patter2 for example -->
    <mat-error *ngIf="longitude.hasError('pattern')"> 
        Longitude must have <strong>a minimum of 5 decimal numbers</strong>
    </mat-error>
</mat-form-field>

我的角色代码:

this.longitude = new FormControl(this.attraction.longitude, [
    // is valid number
    Validators.pattern(new RegExp('(\d{1,3})([.|,]{,1})(\d+))','gi')),
    // is precise enough
    Validators.pattern(new RegExp('(\-{0,1})(\d{1,3})([.|,]{1})(\d{5,13})','i'))
]);

有没有办法给这些模式一个标识符?我会感激任何帮助。

1 个答案:

答案 0 :(得分:6)

不幸的是,无法为Validators提供自定义标识符。

更新17.02.2018 21:00

正如Dawid Zbinski在评论中提到的那样,同一错误的多个错误(例如:&#39;模式&#39;)被覆盖,我更新了我的答案。

创建一个自定义验证器,它将传递正则表达式和预定义的错误作为参数:

&#13;
&#13;
  regexValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      if (!control.value) {
        return null;
      }
      const valid = regex.test(control.value);
      return valid ? null : error;
    };
  }
&#13;
&#13;
&#13;

并像这样使用它:

&#13;
&#13;
  this.longitude = new FormControl('', [
    this.regexValidator(new RegExp('^[0-9]+$'), {'number': ''}),
    this.regexValidator(new RegExp('^.{5,}$'), {'precision': ''})
  ]);
&#13;
  <mat-form-field class="form-field">
    <input matInput placeholder="Logitude" [formControl]="longitude">
    <mat-error *ngIf="longitude.hasError('number')">
        Longitude must be <strong>a number</strong>
    </mat-error>
    <!-- I want to be able to check patter2 for example -->
    <mat-error *ngIf="longitude.hasError('precision')">
        Longitude must have <strong>a minimum of 5 decimal numbers</strong>
    </mat-error>
</mat-form-field>
&#13;
&#13;
&#13;

我还更新了stackblitz演示: https://stackblitz.com/edit/angular-dvwcj3?file=app%2Fhello.component.ts

OLD ANSWER:

PatternValidators正在返回唯一ValidatonErrorObjects

当您从official angular repo的模式验证器检出源代码时,您可以看到它们总是在错误对象中返回正则表达式。

return (control: AbstractControl): ValidationErrors | null => {
  if (isEmptyInputValue(control.value)) {
    return null;  // don't validate empty values to allow optional controls
  }
  const value: string = control.value;
  return regex.test(value) ? null :
                             {'pattern': {'requiredPattern': regexStr, 'actualValue': value}};
};

考虑到这一点,您可以在component.ts文件中轻松创建两个getter方法。它们在两个正则表达式之间有所不同。在此示例中,它们只是检查唯一子字符串是否与正则表达式匹配。当然,他们是处理这个问题的其他方法。

&#13;
&#13;
  get numberError() {
    if (this.longitude && this.longitude.hasError('pattern')) {
      return this.longitude.getError('pattern').requiredPattern.indexOf('(\d+)') !== -1
    }
    return false;
  }

  get preciseError() {
    if (this.longitude && this.longitude.hasError('pattern')) {
      return this.longitude.getError('pattern').requiredPattern.indexOf('(\-{0,1})') !== -1
    }
    return false;
  }
&#13;
&#13;
&#13;

相关问题