I'm trying make a validation for "passwordConfirm" field, but i get a stange error: ERROR TypeError: Cannot read property 'get' of undefined
here is my code:
loginForm: FormGroup;
ngOnInit(){
this.loginForm = new FormGroup({
'email': new FormControl(null, [Validators.required, Validators.email]),
'password': new FormControl(null, Validators.required),
'passwordConfirm': new FormControl(null, [Validators.required, this.checkIfMatchingPasswords.bind(this)]),
});
}
checkIfMatchingPasswords() {
return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : { notSame: true} // error
}
What you are trying to achieve by binding this
to your validator is probably failing as multiple validator functions are merged into a single function where the context is likely different.
However, if you follow the footprint of a validator function, you can do the following:
checkIfMatchingPasswords(control: AbstractControl): ValidationErrors | null {
return control.root.get('password').value === control.value ? null : { notSame: true };
}
The trick is that each AbstractControl
knows its parent and root.