Angular异步验证器无法按预期工作

时间:2019-02-10 16:02:11

标签: javascript angular angular5

我想在angular中实现自定义异步验证器。但是它似乎没有用。 控制台中没有错误。

验证器shouldBeUnique是一个无效的异步验证器 验证器cannotContainSpace是非异步自定义验证器,可以正常工作。 我无法弄清楚出了什么问题。

查看:

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

组件:

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

1 个答案:

答案 0 :(得分:1)

异步验证器应作为第三个参数放置:

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