检查输入控件是否在angular2中具有某种类型的验证器

Check if input control has certain type of vallidator in angular2

我有包装输入字段的组件。在组件中,我从 @Input() inputControl: Control; 接收到 Control 对象。在模板中,如果不需要组件中的输入字段,我有显示消息的跨度。

<span
  class="input-label-caption">
  (optional)
</span>

和输入

<input
    *ngIf="inputMode=='text' || inputMode=='email'"
    type="{{inputMode}}"
    [ngFormControl]="inputControl"
    placeholder="{{placeholder}}"
    class="input-text"
    [disabled]="inputDisabled"
    [ngClass]="{
    'inverted': inverted
    }">

如果 inputControl 对象包含 Validators.required,我如何读取它? 我想知道我是否可以像这样使用它

<span
  class="input-label-caption"
  *ngIf="!inputControl.validators.required"
  >
  (optional)
</span>

你可以尝试使用这个表达式:

<span
  class="input-label-caption"
  *ngIf="!inputControl.errors?.required"
>
  (optional)
</span>

errors 属性包含每个失败的验证器名称一个条目。

我对 errors 属性使用 Elvis 运算符,因为如果没有验证错误,它可以是未定义的。

编辑

根据您的评论,我认为您可以直接使用带有 Validators.required 函数的 === 运算符来检查 "required" 验证器。事实上,验证器只是一个函数,Validators.required 函数用于 "required" 验证。

对应代码如下:

this.hasRequiredValidator = (this.inputControl.validator === Validators.required);

validator 属性是数组的情况下,您需要稍微扩展测试以检查数组中是否存在 Validators.required 函数。

现在模板中的代码将是:

(选修的)

希望对你有帮助, 蒂埃里

我无法使上述工作正常工作,考虑到自 1 月以来对 Angular 的更改,这并不奇怪。使用最新版本的 Angular (2.2.0),您将需要一些东西在你的 class.

中这样
  get required(): boolean { 
    var _validator: any = this.inputControl.validator && this.inputControl.validator(this.inputControl);
    return _validator && _validator.required;
  }

这也将处理您有多个反应形式的验证器的情况,例如

      name: ['', [Validators.required, Validators.minLength(2)]]

有点晚了,但对我有用的是检查控件是否有 validatorasyncValidator 方法。这样你就知道控件是否有一些同步验证器或一些 asyncValidator。 然后如果你想知道你调用了哪些验证器方法。

同步验证:

const getSyncValidators= (control: FormControl) => {
   if(control.validator) {
     return control.validator({} as AbstractControl);
   };
};

异步验证:

const getAsyncValidators= (control: FormControl) => {
   if(control.asyncValidator) {
     return control.asyncValidator({} as AbstractControl);
   };
};

对于异步验证器,您得到一个可观察对象,您看不到异步验证器的名称。

如果你只想知道它有一个异步验证器,这是一种简单的方法。

始终检查 control.validator 或 control.asyncValidator 是否存在,因为没有任何验证器的控件将因函数不存在而抛出错误。