Angular 2 MDF 验证器需要至少两个字段之一

Angular 2 MDF validator to require atleast one of two fields

我有两个输入字段:电子邮件和 phone,如果用户在电子邮件中输入输入,则不需要输入 phone,反之亦然。一次至少需要一个字段。我有模型驱动的表单,我正在尝试为此编写一个自定义验证器函数。到目前为止,我有: 在我的 validator.ts:

import { FormGroup, FormControl } from '@angular/forms';

export function requiredOptional(emailVal: string, phoneVal: string) {
  return (group: FormGroup): {[key: string]: any} => {
    let email = group.controls[emailVal];
    let phone = group.controls[phoneVal];

    if (!email.value|| !phone.value) {
      return {
        isRequired: true
      };
    }
  }
}

在我的 testForm.component.ts:

export class TestFormComponent{
 testForm: FormGroup;

  constructor(public fb: FormBuilder) {
  this.testForm= fb.group({
    email: ['', emailValidator],
    phone: ['', phoneValidator],
    password: ['', Validators.required],
    confirmPassword: ['', Validators.required]
  }, {validator: matchingPasswords('password', 'confirmPassword')},
    {validator: requiredOptional('email', 'phone')}
  )
  }
  onSubmit(value: Object): void {
  console.log(value);
}
}

在我的 testForm.component.html:

    <form [formGroup]="testForm" novalidate (ngSubmit)="testForm.valid && onSubmit(testForm.value)">
    .......
    <input type="email" placeholder="Email*" formControlName="email">
                <div class="form-text error" *ngIf="testForm.controls.email.touched">
                  <div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
                  <div *ngIf="testForm.controls.email.hasError('invalidEmail')">Email is invalid.</div>
                </div>
    .......
    <input type="text" placeholder="Mobile Number*" formControlName="phone">
                <div class="form-text error" *ngIf="testForm.controls.phone.touched">

                  <div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
                  <div *ngIf="testForm.controls.phone.hasError('invalidPhone')">Phone is invalid.</div>
                </div>
.......
<button [disabled]="!testForm.valid" type="submit" class="btn btn-primary pull-right">Sign up</button>
        </form>

但这不起作用,我在 testForm.component.ts: Supplied parameters do not match any signature of call targets

中遇到错误

您可以通过如下组合定义多个验证函数:

export class TestFormComponent{
 testForm: FormGroup;

  constructor(public fb: FormBuilder) {
  this.testForm= fb.group({
    email: ['', emailValidator],
    phone: ['', phoneValidator],
    password: ['', Validators.required],
    confirmPassword: ['', Validators.required]
  }, {validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]})
  }
  onSubmit(value: Object): void {
  console.log(value);
}
}

关注以下变化:

{validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]}

我们可以使用 Validators.compose

来设置验证函数数组,而不是设置匹配密码验证器