更新时间:2023-11-28 19:13:16
而不是在每个formControl上标记验证器,而是为电话号码创建一个嵌套组,然后将验证器应用于该组.在此示例中,我将仅在整个表单上应用验证器.
Instead of marking the validator on each formControl, make a nested group for the phone numbers and apply the validator to that group. In this sample I'll just apply the validator on the whole form.
同样,当应用验证器时,我们需要在字段有效时返回null
.
Also when applying validators we need to return null
when the field is valid.
此外,由于您正在使用Angular材质,因此我们需要添加 ErrorStateMatcher
才能显示mat-errors
. mat-errors
仅在将验证器设置为表单控件而不是表单组时显示.
Also, since you are using Angular material, we need to add a ErrorStateMatcher
to be able to show mat-errors
. mat-errors
show only when validators are set to form control, not a formgroup.
您的代码应如下所示:
createFormGroup() {
this.myForm = this.fb.group({
mobile : new FormControl(''),
homePhone : new FormControl('')
// our custom validator
}, { validator: this.atLeastOnePhoneRequired});
}
atLeastOnePhoneRequired(group : FormGroup) : {[s:string ]: boolean} {
if (group) {
if(group.controls['mobile'].value || group.controls['homePhone'].value) {
return null;
}
}
return {'error': true};
}
错误状态匹配器:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const controlTouched = !!(control && (control.dirty || control.touched));
const controlInvalid = !!(control && control.invalid);
const parentInvalid = !!(control && control.parent && control.parent.invalid && (control.parent.dirty || control.parent.touched));
return (controlTouched && (controlInvalid || parentInvalid));
}
}
在组件中用以下标记:
matcher = new MyErrorStateMatcher();
,然后在两个输入字段上将其标记到您的模板.还要注意*ngIf
看起来如何显示验证消息:
and then mark it to your template on both input fields. Also note how the *ngIf
looks for displaying validation messages:
<mat-form-field>
<input matInput placeholder="Mobile" formControlName="mobile" [errorStateMatcher]="matcher">
<mat-error *ngIf="myForm.hasError('error')">
"Enter either phone number"
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Home Phone" formControlName="homePhone" [errorStateMatcher]="matcher">
<mat-error *ngIf="myForm.hasError('error')">
"Enter either phone number"
</mat-error>
</mat-form-field>
StackBlitz