Angular异步验证器无法按预期工作 [英] Angular Async Validator not working as expected

查看:79
本文介绍了Angular异步验证器无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

查看:

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

推荐答案

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

Async validators should be placed as the third argument:

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

这篇关于Angular异步验证器无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆