use*_*026 4 angular-validation angular angular-reactive-forms
我正在尝试实现自定义验证器功能来检查是否输入了电话号码(家庭电话和移动电话).我想在两个字段上显示错误消息,当它们被触摸并且没有有效值时,由于某种原因我的代码没有按预期工作.请帮帮我这篇文章.-谢谢!这是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;
}
Run Code Online (Sandbox Code Playgroud)
不是在每个formControl上标记验证器,而是为电话号码创建一个嵌套组,并将验证器应用于该组.在这个示例中,我将在整个表单上应用验证器.
同样在应用验证器时,我们需要null在字段有效时返回.
此外,由于您使用的是Angular材质,我们需要添加一个ErrorStateMatcher才能显示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};
}
Run Code Online (Sandbox Code Playgroud)
错误状态匹配器:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
你在组件中标记的:
matcher = new MyErrorStateMatcher();
Run Code Online (Sandbox Code Playgroud)
然后在两个输入字段上将其标记为模板.还要注意*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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2679 次 |
| 最近记录: |