我正在尝试验证密码并在表单中重复密码。喜欢这个
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
this.registerForm = fb.group({
name: ['', Validators.required],
email: ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"), Validators.required])],
passwords: this.fb.group({
password: ['', Validators.compose([Validators.required])],
repassword: ['', Validators.compose([Validators.required])]
}, this.comparePassword)
});
function comparePassword(c: AbstractControl) {
return c.get('password').value === c.get(' repassword').value
}
**我也尝试在comparePassword中传递return false:
comparePassword(c: AbstractControl) {
return false;
}
**但每次都是console.log(this.registerForm.valid);给我真实,但如果我在密码和重复密码中给出不同的输入,它应该返回false。所以请帮助解决这个问题。提前致谢
答案 0 :(得分:1)
奇怪的是:当有效时,自定义验证应return null
。
如果验证失败,您应该返回验证错误{ "comparePassword": true }
所以我认为你的功能应该是:
comparePassword(control: AbstractControl) {
if(control.get('password').value === control.get('repassword').value){
return null;
}
return { “comparePassword”: true };
}
Angular.io Custom validation:该函数接受Angular控件对象,如果控件值有效则返回null或验证错误对象。验证错误对象通常具有一个属性,其名称是验证密钥,' forbiddenName',其值是可以插入错误消息({name})的任意值字典。
答案 1 :(得分:1)
这应该有效
comparePassword = (control: AbstractControl): {[key: string]: boolean} => {
// get values
const password = control.get('password');
const repassword = control.get('repassword');
// if no values, validated as true
if (!password || !repassword) {
return null;
}
// if values match, return null, else nomatch: true
return password.value === repassword.value ? null : { nomatch: true };
};
然后在你的表单构建中,设置:
{validator: this.comparePassword}
在
this.registerForm = fb.group({
name: ['', Validators.required],
email: ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"), Validators.required])],
passwords: this.fb.group({
password: ['', Validators.compose([Validators.required])],
repassword: ['', Validators.compose([Validators.required])]
},{validator: this.comparePassword}) // here
});