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; }
html file, add the ngIf directive to show the message when the form is submitted and the required validator is true. Save the changes and run the app. Click on the sign-in button without entering the first name and you will be able to see the required validation message.
export const passwordMatchValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => { if (formGroup. get('password'). value === formGroup. get('password2').
ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null.
This is what eventually worked for me -
this.addEditUserForm = this.builder.group({ firstName: ['', Validators.required], lastName: ['', Validators.required], title: ['', Validators.required], email: ['', Validators.required], password: ['', Validators.required], confirmPass: ['', Validators.required] },{validator: this.checkIfMatchingPasswords('password', 'confirmPass')}); checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) { return (group: FormGroup) => { let passwordInput = group.controls[passwordKey], passwordConfirmationInput = group.controls[passwordConfirmationKey]; if (passwordInput.value !== passwordConfirmationInput.value) { return passwordConfirmationInput.setErrors({notEquivalent: true}) } else { return passwordConfirmationInput.setErrors(null); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With