Here is a validator function that I have:
export const PasswordsEqualValidator = (): ValidatorFn => {
return (group: FormGroup): Observable<{[key: string]: boolean}> => {
const passwordCtrl: FormControl = <FormControl>group.controls.password;
const passwordAgainCtrl: FormControl = <FormControl>group.controls.passwordAgain;
const valid = passwordCtrl.value.password === passwordAgainCtrl.value.passwordAgain;
return Observable.of(valid ? null : {
passwordsEqual: true
});
};
};
This validator is utilized in the following form:
public signupForm: FormGroup = this.fb.group({
email: ['', Validators.required],
passwords: this.fb.group({
password: ['', Validators.required],
passwordAgain: ['', Validators.required]
}, {validator: CustomValidators.passwordsEqual()})
});
Below is a section of the template where it is implemented:
<div formGroupName="passwords">
<div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
<label class="label" for="password">Password</label>
<input class="input" id="password" formControlName="password" type="password">
</div>
<div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
<label class="label" for="password-again">Password again</label>
<input class="input" id="password-again" formControlName="passwordAgain" type="password">
</div>
</div>
Despite matching passwords, an error is displayed. I’ve explored various solutions to similar issues but many seem cluttered and outdated. Therefore, I am seeking a simpler resolution.
Perhaps a minor tweak is required, yet I am unable to pinpoint it.