【问题标题】:Straightforward custom validation in angular2angular2 中的简单自定义验证
【发布时间】:2017-04-04 16:09:10
【问题描述】:

我已经创建了这个验证函数:

private customValidateField(c: FormControl): any {
    return c.value[0] === 'a' ? null : { notValid: true };
}

所以,在我的反应形式上:

constructor(private fb: FormBuilder)
{
  this.form = this.fb.group({
    field: ['', Validators.required, this.customValidateField],
    ...
  }
}

当我在此字段中写入任何字符时,我会收到此错误:

错误:预期的验证器返回 Promise 或 Observable。

有什么想法吗?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    “字段”数组中的第三项是异步验证器(或它们的数组)。所以要指定多个同步验证器,你需要:

    将它们作为数组传递

    this.fb.group({
      'formControlName': [this.hero.name, [
          Validators.required,
          Validators.minLength(4)
      ]]
    });
    

    或将它们组合起来(如 Jordi 所写)使用

    Validators.compose(...)
    

    FormBuilder API doc没有详细讨论参数,但由于它只是用FormControl-s创建FormGroup的快捷方式,你可以看一下FormControl的构造函数: https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

    【讨论】:

      【解决方案2】:

      我刚刚用过Validators.compose

      this.form = this.fb.group({
        field: ['', Validators.compose([Validators.required, this.validateCardNumber])],
        ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-03
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        • 2016-12-04
        • 1970-01-01
        • 1970-01-01
        • 2018-03-23
        相关资源
        最近更新 更多