Angular,如何为两个字段中的任何一个设置验证应该在反应形式方法中验证

Angular, How to set validation for either of two field should validate in reaction form approach

我正在尝试设置用户表单验证,用户必须输入两个字段之一,手机或电子邮件字段

添加访客反应表Html:

<form class="new_guest" id="new_guest" [formGroup]="addGuestForm" (ngSubmit)="onSubmit()">
            <div class="form-group">
                <input placeholder="Enter guest name" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="name"
                    id="guest_name" autocomplete="off">
            </div>
            <div class="form-group">
                <input placeholder="Enter guest email" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="email"
                    id="guest_email" autocomplete="off">
            </div>
            <div class="form-group">
                <input placeholder="Mobile Number, If any" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="mobile"
                    id="guest_mobile" autocomplete="off">
            </div>
            <input type="submit" class="btn btn-default btn-block" id="add_guest" value="ADD GUEST" [disabled]="!addGuestForm.valid">
        </form

AddGuest 初始化:

this.addGuestForm = new FormGroup({
  'name': new FormControl(null, Validators.required),
  'email': new FormControl(null, Validators.email),
  'mobile': new FormControl(null)
})

有人可以帮忙吗?

您可以使用表单生成器并提供自定义验证,例如:

this.addGuestForm = this.formBuilder.group({
'name': new FormControl(null, Validators.required),
  'email': '',
  'mobile': ''
}, {
      validator: (formControl) => {
        var emailCtrl = formControl.controls.email;
        var mobileCtrl = formControl.controls.mobile;


        if (emailCtrl != undefined && mobileCtrl != undefined)
             if(!(emailCtrl.value.length || mobileCtrl.value.length ))
                    return {invalid: true};
}
});

此外,您还可以检查电子邮件字段的正则表达式 为电子邮件模式检查定义一个变量 regexPattern,并在下面的自定义验证器中使用 if condition

regexPattern.test(emailCtrl.value)

我遇到了同样的问题,我的解决方案是编写自定义验证器:

export function oneOfControlRequired(...controls: AbstractControl[]): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
        for (const aControl of controls) {
          if (!Validators.required(aControl)) {
            return null;
          }
        }
        return { oneOfRequired: true };
     };
}

你可以这样使用:

this.addGuestForm.setValidators([
  oneOfControlRequired(
      this.addGuestForm.get('email'),
      this.addGuestForm.get('mobile'),
  )
]);

也许您想稍微修改 oneOfControlRequired 函数以将 controlNames: string[] 作为输入参数而不是 AbstractControl[]

你可以查看工作示例here

我稍微更改了@pogiaron 的答案所以你可以设置返回的错误键。

static oneControlRequired(errorKey: string, ...controls: AbstractControl[]) {
    return (control: AbstractControl): ValidationErrors | null => {
        for (const aControl of controls) {
          if (!Validators.required(aControl)) {
            return null;
          }
        }
        return { [errorKey]: true };
     };
}