在我的响应式(Reactive)表单中,我为 3 个输入字段构建了自定义验证。验证的主要功能是当 3 个输入字段中的 1/2 有一个值时返回错误(我希望用户在 1 个字段中输入值后,所有 3 个字段都需要)。
这是我的验证器:
public addressValidator(control: AbstractControl): { [key: string]: boolean } | null {
const zip= control.get('zip');
const houseNumber= control.get('houseNumber');
const street= control.get('street');
if ((zip?.value !== "" || houseNumber?.value !== "" || street?.value !== "") &&
(zip?.value === "" || houseNumber?.value === "" || street?.value === "")) {
console.log("form not valid");
return { 'invalid': true };
} return null;
}
ngOnInit:
ngOnInit(): void {
this.contactForm = this.fb.group(
{
addition: "",
residence: ["", [
Validators.required
]],
phone: "",
mobile: "",
address: this.fb.group({
street: ['', [
]],
houseNumber: ['', [
]],
zip: ['', [
]],
}, { validator: this.adresValidator } )
});
HTML:
<ng-container formGroupName="address">
<div class="col-12">
<mat-form-field class="w-100">
<mat-label>Street</mat-label>
<input matInput formControlName="street">
<mat-error *ngIf="street.errors?.invalid">Field is mandatory</mat-error>
</mat-form-field>
</div>
我正在使用 Angular Material 显示错误消息,但即使我的 console.logs 告诉我验证已应用,我似乎无法在模板中显示消息。我已经尝试了 HTML 示例中的代码以及其他一些行,但它们要么已弃用,要么不起作用。
我的问题是,如何在模板中显示错误? (注意:address是一个嵌套的formGroup)
最佳答案
验证器被添加到 this.contactForm
本身。因此错误将出现在 contactForm
组上。
<mat-error *ngIf="contactForm.errors?.invalid">Field is mandatory</mat-error>
关于angular - 显示跨字段自定义验证错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68724286/