简体   繁体   中英

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);
        });
    } 
}

Async validators should be placed as the third argument:

username: new FormControl('', 
          [Validators.required, UsernameValidators.cannotContainSpace],
          [UsernameValidators.shouldBeUnique]),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM