【问题标题】:Angular: Custom validator returning null makes Angular throw an errorAngular:自定义验证器返回 null 使 Angular 抛出错误
【发布时间】:2018-03-03 23:01:36
【问题描述】:

当我在验证 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】:

替换

account.errors.passwordsShouldMatch

通过

account.hasError('passwordsShouldMatch')

正如您在the documentation 中看到的,FormGroup.errors 的类型是ValidationErrors | null。

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2020-04-01
    • 2019-01-07
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多