[英]Adding confirm password validation to Angular Reactive Forms?
I'm following this tutorial for how to validate confirm passwords with Angular Reactive Forms.我正在关注本教程,了解如何使用 Angular Reactive Forms 验证确认密码。
I created a Stackblitz for the implementation.我为实现创建了一个 Stackblitz 。
The implementation for the confirm password function comes from the tutorial and looks like this:确认密码 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);
}
};
}
If I try to add it to a composed validator like this:如果我尝试将它添加到这样的组合验证器中:
confirmPassword: new FormControl(
'',
Validators.compose([
Validators.required,
this.v.passwordMatch('password', 'confirmPassword'),
])
),
Angular creates an error that says: Angular 创建一个错误,上面写着:
ERROR
Error: Cannot read properties of undefined (reading 'password')
How do we add a validator that performs cross property validation?我们如何添加一个执行跨属性验证的验证器?
Right now this Stackblitz Demo works:现在这个 Stackblitz 演示有效:
https://stackblitz.com/edit/angular-ivy-f5dj86?file=src%2Fapp%2Fregistration.component.ts https://stackblitz.com/edit/angular-ivy-f5dj86?file=src%2Fapp%2Fregistration.component.ts
Because the cross password validation is commented out:因为交叉密码验证被注释掉了:
confirmPassword: new FormControl(
'',
Validators.compose([
Validators.required,
// this.v.passwordMatch('password', 'confirmPassword'),
])
),
Since the validator needs access to both password control values to compare them, you have to use it as a FormGroup validator.由于验证器需要访问两个密码控制值来比较它们,因此您必须将其用作 FormGroup 验证器。 So you just have to move the validator to the second argument of the
FormGroup
constructor like this所以你只需要像这样将验证器移动到
FormGroup
构造函数的第二个参数
public registrationForm: FormGroup = new FormGroup({
email: new FormControl(...),
password: new FormControl(...),
confirmPassword: new FormControl(...),
},
this.v.passwordMatch('password', 'confirmPassword')
);
cheers干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.