The simplest way imo:
(It can also be used with emails for example)
public static matchValues(
matchTo: string // name of the control to match to
): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
return !!control.parent &&
!!control.parent.value &&
control.value === control.parent.controls[matchTo].value
? null
: { isMatching: false };
};
}
In your Component:
this.SignUpForm = this.formBuilder.group({
password: [undefined, [Validators.required]],
passwordConfirm: [undefined,
[
Validators.required,
matchValues('password'),
],
],
});
Follow up:
As others pointed out in the comments, if you fix the error by fixing the password
field the error won't go away, Because the validation triggers on passwordConfirm
input. This can be fixed by a number of ways. I think the best is:
this.SignUpForm .controls.password.valueChanges.subscribe(() => {
this.SignUpForm .controls.confirmPassword.updateValueAndValidity();
});
On password
change, revliadte confirmPassword
.