我正在關注本教程,了解如何使用 Angular Reactive Forms 驗證確認密碼。
我為實作創建了一個 Stackblitz。
確認密碼功能的實作來自教程,如下所示:
passwordMatch(password: string, confirmPassword: string) {
return (formGroup: FormGroup) => {
const passwordControl = formGroup.controls[password];
const confirmPasswordControl = formGroup.controls[confirmPassword];
if (!passwordControl || !confirmPasswordControl) {
return null;
}
if (
confirmPasswordControl.errors &&
!confirmPasswordControl.errors.passwordMismatch
) {
return null;
}
if (passwordControl.value !== confirmPasswordControl.value) {
confirmPasswordControl.setErrors({ passwordMismatch: true });
} else {
confirmPasswordControl.setErrors(null);
}
};
}
如果我嘗試將它添加到這樣的組合驗證器中:
confirmPassword: new FormControl(
'',
Validators.compose([
Validators.required,
this.v.passwordMatch('password', 'confirmPassword'),
])
),
Angular 創建一個錯誤,上面寫著:
ERROR
Error: Cannot read properties of undefined (reading 'password')
我們如何添加一個執行跨屬性驗證的驗證器?
現在這個 Stackblitz 演示有效:
https://stackblitz.com/edit/angular-ivy-f5dj86?file=src/app/registration.component.ts
因為交叉密碼驗證被注釋掉了:
confirmPassword: new FormControl(
'',
Validators.compose([
Validators.required,
// this.v.passwordMatch('password', 'confirmPassword'),
])
),
uj5u.com熱心網友回復:
由于驗證器需要訪問兩個密碼控制值來比較它們,因此您必須將其用作 FormGroup 驗證器。所以你只需要FormGroup像這樣將驗證器移動到建構式的第二個引數
public registrationForm: FormGroup = new FormGroup({
email: new FormControl(...),
password: new FormControl(...),
confirmPassword: new FormControl(...),
},
this.v.passwordMatch('password', 'confirmPassword')
);
干杯
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420565.html
標籤:
