未调用表单组异步验证器函数

Use*_*250 0 angular-validation angular angular-forms

我需要实现依赖于多个表单字段的异步验证,所以我将验证放在FormGroup. 但是没有调用验证函数。当然我错过了一些东西。

heroForm: FormGroup;

  ngOnInit(): void {
    this.heroForm = new FormGroup({
      'name': new FormControl(this.hero.name, [
        Validators.required,
        Validators.minLength(4),
        forbiddenNameValidator(/bob/i)
      ]),
      'alterEgo': new FormControl(this.hero.alterEgo, {        
        updateOn: 'blur'
      }),
      'power': new FormControl(this.hero.power, Validators.required)
    }, null,this.validate.bind(this));
  }

  validate(
    ctrl: FormGroup
  ): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    console.log(ctrl)
    return this.heroesService.isAlterEgoTaken(ctrl.controls.alterEgo.value).pipe(
      map(isTaken => { 
        console.log(isTaken);
        return (isTaken ? { uniqueAlterEgo: true } : null)
        }),
      catchError(() => null)
    );
  }
Run Code Online (Sandbox Code Playgroud)

在这里创建了一个演示:https : //stackblitz.com/edit/angular-xtqhqi

Lud*_*vik 7

仅当所有同步验证器都返回 null 时才会触发异步验证器。因此,删除所有表单错误,然后将调用异步验证器。

不要忘记您已updateOn: 'blur'为该输入指定,因此您必须模糊输入以触发验证。

  • “仅当所有同步验证器都返回 null 时才会触发异步验证器”。这就是问题所在。谢谢! (3认同)