2

因此,在 myForm 中,有 2 个字段名称和电子邮件,我想添加验证以检查用户是否输入其中任何一个,它将通过验证;如果两个字段都为空或为空,则失败。

如何编写这样的验证器来满足我的场景?

<form [formGroup]="myForm" novalidate (ngSubmit)="submit(myForm.value)">
<div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-8">
        <div class="card">
            <div class="card-header my-contact-info">
                My Contact Info
            </div>
            <div class="card-block">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Name:</label>
                            <small class="alert" *ngIf="!myForm.controls['name'].valid && myForm.controls['name'].touched">This field is required.</small>
                            <input type="text" class="form-control" formControlName="name">
                        </div>
                        <div class="form-group">
                            <label>Email:</label>
                            <small class="alert" *ngIf="!myForm.controls['email'].valid && myForm.controls['email'].touched">This field is required. Please input a valid email.</small>
                            <input type="text" class="form-control" formControlName="email">
                        </div>
                    </div>
                    <div class="col-md-6">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

    buildForm(): void {
    this.myForm = this._fb.group({
        'name': [null, Validators.compose([Validators.required, Validators.minLength(3)])],
        'email': [null, Validators.compose([Validators.required, Validators.email])]
    });
}
4

1 回答 1

6

我会为此创建一个自定义验证器,例如:

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

export const OneFilledOutValidator = (): ValidatorFn => {

  return (group: FormGroup): {[key: string]: boolean} => {

    const fields = [];

    for (const field in group.controls) {

      if (group.controls.hasOwnProperty(field)) {
        fields.push(group.get(field).value);
      }
    };

    const result = fields.filter(field => !!field);

    const valid = result.length !== 0;

    return valid ? null : {
      oneFilledOut: true
    };
  };
};

这基本上采用一个表单组并检查是否有任何控件具有值。

this.myForm = this._fb.group({
    'name': [null, [Validators.minLength(3)]],
    'email': [null, [Validators.email]]
}, OneFilledOutValidator); // I would wrap this in a CustomValidators constant
于 2017-07-10T11:31:12.753 回答