angularangular-materialangular-material2angular-formsangular-validator

How to use a FormControl with a Custom Validators correctly ? [Angular / Angular Material]


I have a display problem when using a custom Validators on a FormControl. One of my input is mistaken, while no error is present.

enter image description here

Here are my two 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 has a custom error unlike FormControl2, here it is:

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

If the value of the first input is 2, then the error occurs and it works correctly. On the other hand, when the value of the first input is between 0 and 31 and is not equal to 2, my input is displayed in red as if there was still an error, which I do not want.

I would like FormControl1 to work in the same way as FormControl2 which does not display an error because it does not have custom Validators.

HTML code:

<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>

If anyone has a solution to my problem, I am a taker. StackBlitz HERE

Thank you


Solution

  • I found where my problem is. The checkError() function of my validator should not return anything if there is no error:

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