不要在每个 formControl 上标记验证器,而是为电话号码创建一个嵌套组并将验证器应用于该组。在此示例中,我将仅在整个表单上应用验证器。
此外,在应用验证器时我们需要返回null
当该字段有效时。
另外,由于您使用的是 Angular 材质,我们需要添加ErrorStateMatcher https://material.angular.io/components/input/overview#changing-when-error-messages-are-shown能够展示mat-errors
. mat-errors
仅当验证器设置为表单控件而不是表单组时才显示。
您的代码应如下所示:
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
寻找显示验证消息:
<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>
堆栈闪电战 https://stackblitz.com/edit/angular-kcqyse?file=app/input-error-state-matcher-example.html