Reputation: 1424
I'm using a custom validator to check if the values of 2 inputs match:
import { FormGroup } from '@angular/forms';
// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
This works for the matching of 1 pair of inputs, implimented as below:
ngOnInit() {
this.applicationForm = this.formBuilder.group({
firstName: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', Validators.required],
acceptTerms: [false, Validators.requiredTrue]
}, {
validator: MustMatch('password', 'confirmPassword')
});
}
But I can't figure out how to enable it a second time for another pair such as email and confirm email.
Doing
validator: MustMatch('password', 'confirmPassword'), validator2: MustMatch('email', 'confirmEmail')
Doesn't error, but doesn't do anything, the validation still works for password, but not for email. You can't have multiple properties with the same name so I tried with "validator2".
I can't call a whole new
{
validator: MustMatch('password', 'confirmPassword')
}
within this.formBuilder.group({}) as it only takes in 2 arguments.
Upvotes: 0
Views: 210