[英]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.