【发布时间】:2019-02-13 14:22:43
【问题描述】:
我正在尝试为密码制作自定义验证器,但我不明白为什么会出现以下错误 错误类型错误:无法读取未定义的属性“f”
下面是我的代码:
registerForm: FormGroup;
submitted = false;
constructor(private Auth:AuthService, private router:Router,private
formBuilder:FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
userName: ['', Validators.compose([Validators.required,Validators.minLength(6),Validators.maxLength(30),Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')])],
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
cpassword: ['', Validators.required,passwordMatch()] //paswordMatch triggers the error
},);
}
get f() { return this.registerForm.controls; }
function passwordMatch() {
if(this.f != undefined){
let passwordInput = this.f.password,
passwordConfirmationInput = this.f.cpassword;
if (passwordInput.value !== passwordConfirmationInput.value) {
return passwordConfirmationInput.setErrors({notequal: true})
}
else {
return passwordConfirmationInput.setErrors(null);
}
}
}
【问题讨论】:
-
只使用
passwordMatch()而不是function passwordMatch() -
我使用函数是因为密码匹配在组件类之外
-
这不会影响您的
f范围吗? -
我照你说的做了,还是一样的错误,不管我声明那个方法或函数还是一样的输出
-
我会为密码创建一个子组并在那里应用验证器。因为如果用户在输入确认后更改了第一个密码怎么办。即使密码不匹配,表单也是有效的。
标签: angular typescript angular-reactive-forms