Angular2:如何将 Validators.required 设置为 2 个字段的通用验证

Angular2 : how to set Validators.required as common validation for 2 fields

我正在使用 Angular2 ForumBulder 创建表单并添加验证。在组件

的示例代码下方
this.OtpForm = this._fb.group({
    otpInput: this._fb.group({
      otpInput1: ['', Validators.required],
      otpInput2: ['', Validators.required],
      otpInput3: ['', Validators.required],
    }, { validator: this.numericValidator })
});

现在可以正常使用了。但问题是如何 Validators.required 像自定义验证器一样对所有字段通用 numericValidator?

您可以为 otpInput 组再创建一个自定义验证器,例如

validateAllRequired(g: FormGroup) {
    let ctrls = g.controls;
    let keys = Object.keys(ctrls);
    let valid = true;
    keys.forEach((key) => {
      let ctrl = ctrls[key];
      if (ctrl.value.trim() == '') {
        valid = false;
      }
    });
    return valid ? null : {
      validateAllRequired: {
        valid: valid
      }
    };
}

并添加到此:

otpInput: this._fb.group({
  otpInput1: [''],
  otpInput2: [''],
  otpInput3: [''],
}, { validator: Validators.compose([this.numericValidator, this.validateAllRequired]) })

使用 Validators.compose()

组合验证器
Validators.compose([...])

异步验证器使用

Validators.composeAsync([...])