S_NoBEl
S_NoBEl

Reputation: 111

Angular not entering custom form validation

I'm trying to create a password match validation in a register form, but Angular never enters the custom validation, and I cannot seem to figure out why. The form is as follows.

this.userSettingsForm = this.fb.group({
  username: [
    '',
    [
      Validators.required,
      Validators.minLength(4)
    ]
  ],
  password: [''],
  password_confirm: ['']
},
{
  Validator: this.passwordMatchValidator
});

The validation function is the following;

passwordMatchValidator() {
  const password = this.userSettingsForm.get('password').value;
  const confirmPassword = this.userSettingsForm.get('password_confirm').value;

  if(password.errors && !confirmPassword.errors.passwordMatchValidator) {
    return;
  }

  if(password !== confirmPassword) {
    confirmPassword.setErrors({ notSame: true});
  }
  else {
    confirmPassword.setErrors(null);
  }
}

Using the following to display errors

<ng-container *ngIf="userSettingsForm.controls.password_confirm.errors">
  {{ userSettingsForm.controls.password_confirm.errors.message }}
</ng-container>

But the form always submits as valid. What do I miss?

Upvotes: 0

Views: 273

Answers (1)

AVJT82
AVJT82

Reputation: 73377

First of all, you are using Validator instead of validators where you are declaring your custom validator in the form.

Then we need to properly call the validation function, also I suggest you actually put the error on the form group itself, but that is perhaps just a preference. Anyway, I suggest the following:

constructor(private fb: FormBuilder) {
  this.userSettingsForm = this.fb.group(
    {
      password: ['', Validators.required],
      password_confirm: ['', Validators.required]
    },
    { validators: this.passwordMatchValidator() } // should be "validators"
  );
}

and the validator I suggest this:

passwordMatchValidator(): ValidatorFn {
  return (form: AbstractControl): ValidationErrors | null => {
    const password = form.get('password').value;
    const confirmPassword = form.get('password_confirm').value;
    return password === confirmPassword ? null : { notSame: true };
  };
}

Then you can display the error with userSettingsForm.hasError('notSame')

A DEMO for reference.

Upvotes: 2

Related Questions