Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Async Validator not working as expected

I am tying to implement custom async validator in angular. But it does not seem to be working. There are no errors in the console.

validator shouldBeUnique is an async validator which is not working validator cannotContainSpace is non async custom validator which works just fine. I am not able to figure out what went wrong.

View:

<form [formGroup]="form">
    <div class="form-group">
        <label for="username">Username</label>
        <input 
        formControlName="username"
            id="username" 
            type="text" 
            class="form-control">

            <div *ngIf="username.errors.cannotContainSpace" class="alert alert-danger">Can not have space</div>
            <div *ngIf="username.errors.shouldBeUnique" class="alert alert-danger">shouldBeUniquee</div>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input 
        formControlName="password"
            id="password" 
            type="text" 
            class="form-control">
    </div>
    <button class="btn btn-primary" type="submit">Sign Up</button>
</form>

Component:

export class SignupFormComponent {
  form = new FormGroup(
    {
      username: new FormControl('', [Validators.required,
      UsernameValidators.cannotContainSpace, UsernameValidators.shouldBeUnique
      ]),
      password: new FormControl('', Validators.required),


    });

  get username() {
    console.log(this.form.get('username').errors.shouldBeUnique);
    return this.form.get('username');
  }
}

username.validator.ts

export class UsernameValidators {
    static cannotContainSpace(control: AbstractControl): ValidationErrors | null {
        if ((control.value as string).indexOf(' ') != -1) {
            console.log('noo');
            return { cannotContainSpace: true };
        }
        else {
            return null;
        }
    }

    static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {

        return new Promise((resolve, reject) => {
            setTimeout(() => { 
                if (control.value === 'arbaaz')
                    resolve( { shouldBeUnique: false });
                    else                  
                    resolve(null); 
            }, 2000);
        });
    } 
}
like image 402
SamuraiJack Avatar asked Aug 07 '26 02:08

SamuraiJack


1 Answers

Async validators should be placed as the third argument:

username: new FormControl('', 
          [Validators.required, UsernameValidators.cannotContainSpace],
          [UsernameValidators.shouldBeUnique]),
like image 108
AT82 Avatar answered Aug 08 '26 15:08

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!