I got this validator:
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
});
};
};
Which is used in this form:
public signupForm: FormGroup = this.fb.group({
email: ['', Validators.required],
passwords: this.fb.group({
password: ['', Validators.required],
passwordAgain: ['', Validators.required]
}, {validator: CustomValidators.passwordsEqual()})
});
Part of the template which uses it:
<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>
The problem is that even when the passwords match, it still shows the error. I've looked at a number of different similar questions but most of em are a bit cluttered and outdated so I wanted to write a cleaner solution.
I'm guessing there's just a small adjustment needed but I just can't seem to figure it out.