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

时间:2016-12-11 12:48:21

标签: validation angular mdf

我有两个输入字段:电子邮件和电话,如果用户在电子邮件中输入输入,则不需要电话输入,反之亦然。至少需要其中一个字段。我有模型驱动的形式,我正在尝试为此编写自定义验证器功能。到目前为止我有: 在我的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

中收到错误

1 个答案:

答案 0 :(得分:1)

您可以通过如下组成来定义多个验证功能:

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设置验证函数数组,而不是设置matchingPasswords验证器