2

I am trying to use a custom validator with the required validator in reactive forms. The logic for the custom validator works correctly and displays its error message correctly. However, when tracing through the code, the required validator always returns true. As a result, the form control is invalid and remains red on the front end even though there is valid user input in the form.

I tried removing the custom validator from the form control, and the required validator behaves normally. Not sure why when used with the custom validator, the required error is always true.

Component.ts

public AbsenceTypeName = new FormControl("", [Validators.required, 
     this.ValidateAbsenceTypeName.bind(this)]);

ValidateUserName(control: AbstractControl): any {

     const userName = control.value;

     const existingUserName = this.users.find(
       user =>
         user.userName.toUpperCase() ===
         userName.toUpperCase()) ? true : null;

     return { existingUserName: existingUserName };
}

Component.html

<mat-form-field>
     <input matInput placeholder="User Name [formControl]="UserName" 
          required maxlength="100" />
     <mat-error *ngIf="UserName.hasError('required')">User Name is required.
          </mat-error>
     <mat-error *ngIf="UserName.hasError('existingUserName')">User 
          Name already exists!</mat-error>
</mat-form-field>

1 Answer 1

0

custom validator can return 2 values - if your validation did not fail : NULL if validation failed : {object: "value"}

so change your code according that, something like this :

ValidateUserName(control: AbstractControl): any {

     const userName = control.value;

     const existingUserName = this.users.find(
       user =>
         user.userName.toUpperCase() ===
         userName.toUpperCase()) ? true : null;

     return existingUserName? {existingUserName:"true"} : null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.