注册按钮仅在signupForm有效时启用,但现在我有一个问题,即使密码和确认密码不匹配,该按钮也会启用
是我的this.equalWithPasswordValidator。实现错误?
你知道吗?谢谢。
# html代码<button mat-raised-button class="full-width v-btn-lrg mt-0px" color="primary" type="submit"
[disabled]="signupForm.invalid">
{{labels.BUTTON.SETUP}}
</button>
# ts代码
this.signupForm = this.fb.group({
confirmPassword: [
'',
[Validators.required, this.equalWithPasswordValidator.bind(this)],
],
password: [
'',
[
this.validatePasswordRequired,
this.validateMinimumPassword,
this.validatePasswordUpperCase,
this.validatePasswordLowerCase,
this.validatePasswordSpecialCharacter,
this.validateOneNumber,
],
],
});
}
equalWithPasswordValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const equal = control.value === this.signupForm.get('password').value;
return equal ? { notEqual: { value: 'Passwords do not match' } } : null;
};
}
您需要向FormGroup应用验证器,以便您可以访问这两个控件。下面是创建验证器来比较两个字段的一种方法…
// component
form = new FormGroup({
password: new FormControl('', [ yourValidators... ]),
confirmPassword: new FormControl('', [ yourValidators... ])
}, {
validators: [ equivalentValidator('password', 'confirmPassword') ]
});
// equivalent.validator.ts
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const equivalentValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
return (control: AbstractControl): ValidationErrors | null => {
const firstControl = control.get(firstControlName);
const secondControl = control.get(secondControlName);
if (secondControl.value && secondControl.value !== firstControl.value) {
secondControl.setErrors({ notEqual: true });
}
return null;
};
};
在这个例子中,我只在第二个字段与第一个字段不匹配时设置错误。这里没有设置错误信息,我只是设置了一个错误值notEqual
,这样验证器就可以跨窗体重用了。