首页 > 解决方案 > 显示跨字段自定义验证错误信息

问题描述

在我的反应式表单中,我为 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 示例中的代码以及其他一些行,但它们要么已被弃用,要么无法正常工作。

我的问题是,如何在模板中显示错误?(注意:地址是一个嵌套的 formGroup )

标签: angularvalidationangular-materialangular-reactive-formsangular-custom-validators

解决方案


验证器被添加到this.contactForm自身。所以错误将在contactForm组上。

<mat-error *ngIf="contactForm.errors?.invalid">Field is mandatory</mat-error>

推荐阅读