我得到了这个验证器:
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
});
};
};
以这种形式使用:
public signupForm: FormGroup = this.fb.group({
email: ['', Validators.required],
passwords: this.fb.group({
password: ['', Validators.required],
passwordAgain: ['', Validators.required]
}, {validator: CustomValidators.passwordsEqual()})
});
使用它的模板的一部分:
<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>
问题是即使密码匹配,它仍然显示错误。我查看了许多不同的类似问题,但大多数问题都有些混乱和过时,所以我想写一个更简洁的解决方案。
我猜只需要进行一些小的调整,但我似乎无法弄清楚。