我已经以如下 Angular 创建了响应式(Reactive)表单,我的问题是,如果密码不匹配,我想禁用表单提交按钮。
表单提交按钮代码
<button [disabled]="changePasswordForm.invalid">Change password</button>
响应式(Reactive)表单代码
this.changePasswordForm = this.fb.group({
oldPassword: ['', [Validators.required, Validators.minLength(10)]],
newPassword: ['', [Validators.required, Validators.minLength(10)]],
newConfirmPassword: ['', [Validators.required, Validators.minLength(10)]]
}, {
validator: this.passwordMatchValidator
});
密码验证器代码
passwordMatchValidator(AC: AbstractControl) {
let newPassword = AC.get('newPassword').value;
let newConfirmPassword = AC.get('newConfirmPassword').value;
if (newPassword !== newConfirmPassword) {
console.log("Passwords doesn't match.");
} else {
console.log("Passwords matched.");
}
}
在用户输入最小长度为 10 个字符的密码之前,表单的提交按钮不会启用。但即使密码不匹配,表单按钮也会被启用。我在这里缺少什么逻辑?
感谢您的帮助。
最佳答案
您的签名是passwordMatchValidator(AC: AbstractControl)
,但您似乎将验证器绑定(bind)到您的表单。
否则,您不会从验证器返回任何内容,您希望它如何验证?尝试这个。
passwordMatchValidator(AC: AbstractControl) {
let newPassword = AC.get('newPassword').value;
let newConfirmPassword = AC.get('newConfirmPassword').value;
return { passwordMismatch: newPassword !== newConfirmPassword };
}
关于javascript - 自定义验证不禁用表单提交按钮 - Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753400/