[英]When using a custom validator, formBuilder.group is displayed as deprecated
我已经按如下方式构建了我的 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 之后的 Aufrauf 组显示为已弃用。 我该如何解决这个问题? 你有什么主意吗?
具有索引类型的 FormGroup 方法在 Angular 11+ 中已弃用,现在我们需要将验证器作为配置选项提供给 formGroup
更改validator ==> 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);
}
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.