I need to check whether password and confirm password fields have same value using reactive form angular2. I did see a lot of answers on the same here,Angular 2 form validating for repeat password ,Comparing fields in validator with angular2, but none seemed to work for me.Can someone please help."this" is undefined in my validate function :( . Sharing my code,
this.addEditUserForm = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
title: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
confirmPass: ['', [Validators.required, this.validatePasswordConfirmation]]
});
validatePasswordConfirmation(group: FormGroup): any{
let valid = true;
// if (this.addEditUserForm.controls.password != this.addEditUserForm.controls.confirmPass) {
// valid = false;
// this.addEditUserForm.controls.confirmPass.setErrors({validatePasswordConfirmation: true});
// }
return valid;
}
This is what eventually worked for me -
Best would be to have a nested group inside the form group, where we have a custom validator checking the form group with
password
andconfirmPass
, so when either of the fields are changed, the validator is fired, as of previously it only fires whenconfirmPass
field is modified.So instead do something like this inside the outer formgroup:
and then the validator could look like this:
Showing the validation error could then be done like this:
Of course you don't need to have a nested group, but it's better to not have the custom validator fire every time when any changes happen to the form. This way it's only fired when changes happen to this inner form group.
If you want to do it that way, you need bind the function to the current "this" context. Pass over
this.validatePasswordConfirmation.bind(this)
but note that this function will be passed the FormControl for the confirmation, and not the FormGroup like you stated in the function signature.I did a different approach that will work for any control. First I define the basic controls of the form:
Then I create a new control to confirm the value with my custom validator:
The code of the
sameValueAs
validator is as follows, you can define it on a separte file to be used anywhereIf you don't want to go through a custom validator you can just create a input field that is standalone and therefore will not compute in your formGroup but rather through ngModel
<input type="password" matInput [(ngModel)]="passwordConfirm" [ngModelOptions]="{standalone: true}">
Then in your ts you can just validate and throw error or invalidate the form if you want. Just found it slightly quicker and practical:
// Check Passwords Match