我已經按如下方式構建了我的 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 組顯示為已棄用。我該如何解決這個問題?你有什么主意嗎?
uj5u.com熱心網友回復:
具有索引型別的 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);
}
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488879.html
標籤:javascript 有角度的 打字稿 验证 角反应形式
