[英]Adding confirm password validation to Angular Reactive Forms?
我正在關注本教程,了解如何使用 Angular Reactive Forms 驗證確認密碼。
我為實現創建了一個 Stackblitz 。
確認密碼 function 的實現來自教程,如下所示:
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%2Fapp%2Fregistration.component.ts
因為交叉密碼驗證被注釋掉了:
confirmPassword: new FormControl(
'',
Validators.compose([
Validators.required,
// this.v.passwordMatch('password', 'confirmPassword'),
])
),
由於驗證器需要訪問兩個密碼控制值來比較它們,因此您必須將其用作 FormGroup 驗證器。 所以你只需要像這樣將驗證器移動到FormGroup
構造函數的第二個參數
public registrationForm: FormGroup = new FormGroup({
email: new FormControl(...),
password: new FormControl(...),
confirmPassword: new FormControl(...),
},
this.v.passwordMatch('password', 'confirmPassword')
);
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.