首页 > 解决方案 > 如何正确使用带有自定义验证器的 FormControl?[角/角材料]

问题描述

ValidatorsFormControl. _ 我的输入之一是错误的,但不存在错误。

在此处输入图像描述

这是我的两个FormControl:

FormControl1 = new FormControl({ value: 0, disabled: false }, [Validators.required, Validators.min(0), Validators.max(31), Validators.compose([this.checkError])]);
FormControl2 = new FormControl({ value: 0, disabled: false }, [Validators.required, Validators.min(0), Validators.max(31)]);

FormControl1有一个自定义错误,不像FormControl2,这里是:

checkError(fieldControl: FormControl): { [s: string]: boolean } {
    console.log(fieldControl);
    if (fieldControl.value === 2) {
        return { error: true }
    } else {
        return { error: false }
    }
}

如果第一个输入的值为 2,则错误发生并且可以正常工作。另一方面,当第一个输入的值在 0 到 31 之间且不等于 2 时,我的输入显示为红色,好像还有错误,这是我不想要的。

我想FormControl1以与 which 不显示错误相同的方式工作,FormControl2因为它没有 custom Validators

HTML 代码:

<mat-form-field class="px-3 mb-1">
    <input matInput [formControl]="FormControl1" placeholder="VALUE 1" (blur)="update()" type="number" required>
    <mat-error *ngIf="FormControl1.hasError('required')">FormControl1 *</mat-error>
    <mat-error *ngIf="FormControl1.hasError('min')">FormControl1 > 0</mat-error>
    <mat-error *ngIf="FormControl1.hasError('max')">FormControl1 < 31</mat-error>
    <mat-error *ngIf="FormControl1.hasError('error')">TEST error "2"</mat-error>
</mat-form-field>
<mat-form-field class="px-3 mb-1">
    <input matInput [formControl]="FormControl2" placeholder="VALUE 2" (blur)="update()" type="number" required>
    <mat-error *ngIf="FormControl2.hasError('required')">FormControl2 *</mat-error>
    <mat-error *ngIf="FormControl2.hasError('min')">FormControl2 > 0</mat-error>
    <mat-error *ngIf="FormControl2.hasError('max')">FormControl2 < 31</mat-error>
</mat-form-field>

如果有人能解决我的问题,我就是接受者。StackBlitz 这里

谢谢

标签: angularangular-materialangular-material2angular-formsangular-validator

解决方案


我发现我的问题出在哪里。如果没有错误, my的checkError()函数不应返回任何内容:validator

checkError(fieldControl: FormControl): { [s: string]: boolean } {
    console.log(fieldControl);
    if (fieldControl.value === 2) {
        return { error: true }
    }
}

推荐阅读