如何在 Angular 中将多个字段验证为一个字段?

How do validate multiple fields as one in Angular?

我正在构建一个 Angular 5 表单。我需要在我的表格(电子邮件或 phone)上提供联系信息。需要电子邮件地址或 phone 号码,但不能同时提供。我将如何为这种情况创建自定义验证器?从 docs 来看,验证器似乎只负责一个控件,而我的验证器需要知道多个控件才能检查它们的所有值。

ngOnInit() {
   this.form = this.formBuilder.group({
       'name': [null, [Validators.required]],
       'email': [null, []], // A user can provide email OR phone, but
       'phone': [null, []], // both are not required. How would you do this?
   });
}

一个可能的解决方案是声明一个将表单本身作为参数的函数,例如:

    export function emailAndPhone() {
      return (form: FormGroup): {[key: string]: any} => {
        return (form.value.phone && form.value.email) ||
               (!form.value.phone && !form.value.email) 
                  ? { emailAndPhoneError : true } 
                  : null;
      };
    }

使用 validator extras 将验证器函数设置为您的表单定义:

ngOnInit() {
   this.form = this.formBuilder.group({
       'name': [null, [Validators.required]],
       'email': [null, []], // A user can provide email OR phone, but
       'phone': [null, []], // both are not required. How would you do this?
   }, { validator: emailAndPhone() });
}

如果您需要识别验证何时检测到无效输入,只需确保之前定义的 emailAndPhoneError 出现在表单错误列表中即可。像这样

*ngIf="myForm.hasError('emailAndPhoneError')" //true means invalid