Angular 4 reactive forms retype password on signup (group validation)
Angular 4 was released recently and as a result there aren’t many community answers for this version. I was working on the sign up page for my latest project and I took a few wrong turns when designing the “retype password” field in a reactive form.
My original thought process was to attach a control validator onto the second password field which would access the parent. Here is an example of this validator:
static equalTo(equalControlName): ValidatorFn {
return (control: AbstractControl): {
[key: string]: any
} => {
if (!control['_parent']) return null;
if (!control['_parent'].controls[equalControlName])
throw new TypeError('Form Control ' + equalControlName + ' does not exists.');
var controlMatch = control['_parent'].controls[equalControlName];
return controlMatch.value == control.value ? null : {
'equalTo': true
};
};
}
}
This solution might work for Angular 2 but for Angular 4 there is a much simpler method with the only downside being it doesn’t work with Form Builder as far as I know.
The second and third args for the Form Group initializer are for group level validators. These can validate multiple controls on a single form and are perfect for this password confirmation.
const form = new FormGroup({
password: new FormControl('', Validators.minLength(2)),
passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);
function passwordMatchValidator(g: FormGroup) {
return g.get('password').value === g.get('passwordConfirm').value
? null : {'mismatch': true};
}
This passwordMatchValidator simply takes a FormGroup (you don’t have to care about this because it is handled by Angular) and returns a validator response when the values of the controls form the passed FormGroup are equal.
Hope this helps!