验证后使表单有效时出现问题 调用函数



我在密码验证字段方面遇到问题。在我的表格中,我有3个字段,一个是旧密码,另一个是新密码以及确认新密码。到目前为止,如果用户输入新密码并确认密码,则表单将生效并且他可以提交,则一切正常。现在,如果字段不匹配并且他编辑了确认密码,它将有效。但是,如果他对新密码进行编辑,则不会。

下面是检查 2 个字段的功能,当我更改任一密码字段时,我看到它被触发,但它仅在最后一次确认更改时使表单有效。

static passwordMatchValidator(control: AbstractControl) {
const password: string = control.get('newPassword').value; // get password from our password form control
const confirmPassword: string = control.get('confirmPassword').value; // get password from our confirmPassword form control
// compare is the password math
if (password !== confirmPassword) {
// if they don't match, set an error in our confirmPassword form control
console.log('No mathch' + password + ' - ' + confirmPassword)
control.get('confirmPassword').setErrors({ NoPassswordMatch: true });
}
//  else {
//    control.get('confirmPassword').setErrors({ NoPassswordMatch: false});
//   }
}

这里也是一个堆栈闪电战示例,演示了此问题。请忽略布局,因为我不想花太多时间让它看起来与我的应用程序中相同

堆栈闪电战示例

您可以按如下方式重置错误:

control.get('confirmPassword').setErrors(null);

如果密码不匹配,您可以简单地返回一个对象(解释错误(

static passwordMatchValidator(control: AbstractControl) {
const password: string = control.get('newPassword').value; // get password from our password form control
const confirmPassword: string = control.get('confirmPassword').value; // get password from our confirmPassword form control
// compare is the password math
if (password !== confirmPassword) {
return {matchError: 'Passwords do not match'}
}
}

https://stackblitz.com/edit/password-validation-zfzxpg?file=src%2Fapp%2Fpassword%2Fcustom-validators.ts

最新更新