angularangular2-formscustom-validators

Angular: Custom validator returning null makes Angular throw an error


When I try to return null while validating a FormControlObject the browser says that it can not read the property of [FormControlObject].errors.errorProperty because its null. Am I missing here something? If I return { errorProperty: false } it all works.

The code:

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

SOLUTION:

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

I have commented out the solution to this problem, but following the documentation, you should be able to return null without a problem. This question might be a duplicate to this thread, but since that was asked 9 months ago and also did not resolve this potential problem I think it is ok to ask again.

Problem reproduced: https://stackblitz.com/edit/angular-d5utxs


Solution

  • Replace

    account.errors.passwordsShouldMatch
    

    by

    account.hasError('passwordsShouldMatch')
    

    As you can see in the documentation, the type of FormGroup.errors is ValidationErrors | null.