【问题标题】:Form group async validator function not getting called表单组异步验证器函数未被调用
【发布时间】:2018-10-29 23:00:27
【问题描述】:

我需要实现依赖于多个表单字段的异步验证,所以我将验证放在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)
    );
  }

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

【问题讨论】:

  • 试过你的演示,验证函数被正确调用。为什么你认为它没有被调用?
  • @Ludevik 在alterEgo 字段中进行任何更改时不会被调用。请重新检查。
  • alterEgo 指定了updateOn: 'blur'。尝试写一些东西,然后模糊输入。
  • 不起作用,尽管从中删除 updateOn:'blur' 有效。所以,似乎没有正确使用它。
  • updateOn: 'blur' 对我有用,但只有当我第一次通过输入其他输入触发验证器时。当我第一次导航到页面并模糊该输入时,它就不起作用了。奇怪

标签: angular angular-forms angular-validation


【解决方案1】:

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

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

【讨论】:

  • “只有当所有同步验证器都返回 null 时才会触发异步验证器”。这就是问题所在。谢谢!
  • 非常感谢。我被这个愚蠢的事情困了几个小时,哈哈。
猜你喜欢
  • 2021-05-23
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 2016-07-26
相关资源
最近更新 更多