gpt4 book ai didi

Angular 2 自定义验证器检查何时需要两个字段之一

转载 作者:太空狗 更新时间:2023-10-29 17:49:42 26 4
gpt4 key购买 nike

我正在尝试实现自定义验证器功能来检查是否输入了电话号码(家庭电话和手机)。当它们都被触摸但没有有效值时,我想在两个字段上显示错误消息,由于某种原因我的代码没有按预期工作。请帮我解决这个问题。 -谢谢!这是 stackblitz 链接 https://stackblitz.com/edit/angular-ve5ctu

createFormGroup() {
this.myForm = this.fb.group({
mobile : new FormControl('', [this.atLeastOnePhoneRequired]),
homePhone : new FormControl('', [this.atLeastOnePhoneRequired])
});
}

atLeastOnePhoneRequired(control : AbstractControl) : {[s:string ]: boolean} {
const group = control.parent;
if (group) {
if(group.controls['mobile'].value || group.controls['homePhone'].value) {
return;
}
}
let errorObj = {'error': false};
return errorObj;
}

最佳答案

不是在每个 formControl 上标记验证器,而是为电话号码创建一个嵌套组并将验证器应用于该组。在此示例中,我将只对整个表单应用验证器。

此外,在应用验证器时,我们需要在字段有效时返回 null

此外,由于您使用的是 Angular Material ,我们需要添加 ErrorStateMatcher能够显示 mat-errorsmat-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>

StackBlitz

关于Angular 2 自定义验证器检查何时需要两个字段之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com