Angular:返回null的自定义验证器使Angular抛出错误

问题描述 投票:1回答:1

当我在验证FormControlObject时尝​​试返回null时,浏览器说它无法读取[FormControlObject] .errors.errorProperty的属性,因为它为null。我在这里错过了什么吗?如果我返回{errorProperty:false}则一切正常。

代码:

    static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
  let newPassword = control.get('password');
  let repeatedPassword = control.get('repeatedPassword');

  if (newPassword.value !== repeatedPassword.value) {
    return { passwordsShouldMatch: true };
  }
  return null;
}

解:

    static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
  let newPassword = control.get('password');
  let repeatedPassword = control.get('repeatedPassword');

  if (newPassword.value !== repeatedPassword.value) {
    return { passwordsShouldMatch: true };
  }
  return {passwordsShouldMatch: false};
}

我已经注释掉了这个问题的解决方案,但是根据文档,你应该能够毫无问题地返回null。这个问题可能与此thread重复,但由于9个月前被问到并且也没有解决这个潜在的问题,我认为可以再问一次。

问题转载:https://stackblitz.com/edit/angular-d5utxs

angular angular2-forms custom-validators
1个回答
0
投票

更换

account.errors.passwordsShouldMatch

通过

account.hasError('passwordsShouldMatch')

正如你在the documentation中看到的那样,FormGroup.errors的类型是ValidationErrors | null

© www.soinside.com 2019 - 2024. All rights reserved.