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 }); }; };
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 that 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 an error. I looked at several similar questions, but most of them were a bit cluttered and outdated, so I wanted to write a cleaner solution.
I suppose that only a small adjustment is required, but I just can't figure it out.
source share