简体   繁体   English

Angular Form内置验证器错误对象键

[英]Angular Form built-in validators error object-keys

Where can I get the the error object keys list of the built-in Validators ? 在哪里可以获得内置验证器错误对象键列表?

For example, if a field uses the required built-in validator, then I can check: 例如,如果一个字段使用required内置验证器,那么我可以检查:

form.get('myField').hasError('required')

but not all the error object keys have the same name as the validator. 但并非所有错误对象键都具有与验证程序相同的名称。

For example, if I use the maxLength validator, then the following will not work: 例如,如果我使用maxLength验证程序,则以下操作将无效

form.get('myField').hasError('maxLength')

It is possible to check those values looking directly at the source code: 可以直接在源代码中检查这些值:

https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts


In my specific case, the object key error for the maxLength validator is maxlength (with lower case L). 在我的特定情况下, maxLength验证程序的对象键错误为maxlength (小写L)。

I figured it out by looking its implementation in the source code, currently: 我通过查看当前在源代码中的实现来弄清楚了:

  static maxLength(maxLength: number): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const length: number = control.value ? control.value.length : 0;
      return length > maxLength ?
          {'maxlength': {'requiredLength': maxLength, 'actualLength': length}} :
          null;
    };
  }

so I'm using: 所以我正在使用:

form.get('myField').hasError('maxlength')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM