I have a custom validator to check retype confirm
import { AbstractControl } from '@angular/forms';
export function RetypeConfirm(confirmpassword: string) {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== confirmpassword) {
return { 'mismatch': true };
}
return null;
};
}
My typescript file
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { RetypeConfirm } from 'app/validators/retype-confirm.validator';
passwordChangeForm: FormGroup;
constructor(private fb: FormBuilder){
this.passwordChangeForm = this.fb.group({
newPassword: ["", [Validators.required, Validators.pattern(RegEx.STRONG_PASSWORD)]],
confirmpassword: ["", [Validators.required, RetypeConfirm(***I want to pass passwordChangeForm.controls['newPassword'].value here**** )]]
});
}
I need to pass this.passwordChangeForm.controls['newPassword'].value
to RetypeConfirm custom validator
Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.
A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.
The validator function needs to return null if no errors were found in the field value, meaning that the value is valid. If any validation errors are found, the function needs to return an object of type ValidationErrors.
To make our custom validator accessible for template-driven forms, we need to implement our validator as a directive and provide it as NG_VALIDATORS . The Directive implements the Validator interface from @angular/forms which forces us to implement the validate method.
The function get the password field and compare with confirm password
function RetypeConfirm(newpassword: string): ValidatorFn {
return (control: FormControl) => {
if (!control || !control.parent) {
return null;
}
return control.parent.get(newpassword).value === control.value ? null : { mismatch: true };
};
}
And you can directly pass the value of password from group
this.signUpForm = this.fb.group({
newpassword: ['', [Validators.required]],
confirmPassword: ['', [
Validators.required,
RetypeConfirm('newpassword')
]]
});
And the html,
<form [formGroup]="signUpForm">
<label>New Password</label>
<input formControlName="newpassword" />
<br>
<label> Confirm Password</label>
<input name="confirmPassword" formControlName="confirmPassword"/>
<span *ngIf=" signUpForm.get('confirmPassword').errors?.mismatch">Password Confirmation must match password</span>
</form>
Working Stackblitz.
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