我已经建立了我的PasswordValidator如下:
// Function to compare password with confirmPassword
export function ConfirmedValidator(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true });
} else {
matchingControl.setErrors(null);
}
};
}
我已经在ngOnInit中创建了表单:
ngOnInit() {
// Create user password form
this.cupForm = this.formBuilder.group( {
password: [null, Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$')],
confirm_password: [null, Validators.required]
}, {
validator: ConfirmedValidator('password', 'confirm_password')
});
}
验证器可以工作,但是formBuilder之后的aufraf组显示为已弃用。我该如何解决这个问题?你知道吗?
带索引类型的FormGroup方法在angular 11+中已弃用,现在我们需要为FormGroup
提供验证器作为配置选项。Changevalidator ==> validators
this.cupForm = this.formBuilder.group( {
password: [null, Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$')],
confirm_password: [null, Validators.required]
}, {
validators: ConfirmedValidator('password', 'confirm_password')
});
然后将返回类型ValidationErrors|null
添加到customValidator方法
export function ConfirmedValidator(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup):ValidationErrors|null => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true });
} else {
matchingControl.setErrors(null);
}
};
}