因此,在 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])]
});
}