我正在使用Form Controls,我认为我已经很好地掌握了。现在我有一个创建控件并分配各自验证器的函数。
对于this.password1:FormControl
和this.password2:FormControl
,应该有一个错误对象,例如errors:{required: true, pattern:true}
。但是,pattern
属性不会出现在任何一个的errors对象中。我甚至在Validators.minLength(8)
中添加了this.password2
FormControl以查看它是否有效,并且minLength错误属性也没有出现。反面是'this.email'与errors: {required: true, email: true}
有正确的错误。
注意:当我测试表单的有效性时。它确实进行模式检查和最小长度检查。我只是无法访问应该创建的错误属性。当我在console.log上时,我得到的FormContril上的errors属性是errors:{required: true}
。
任何帮助都将被理解为什么不创建错误属性。感恩节快乐!
ngOnInit() {
this.title.setTitle(this.pageTitle);
this.createFormControls();
this.createForm();
}
createFormControls(): void {
const mediumRegex = new RegExp('(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})');
this.email = new FormControl('', Validators.compose([Validators.required, Validators.email]));
this.firstName = new FormControl('', Validators.compose([Validators.required]));
this.lastName = new FormControl('', Validators.compose([Validators.required]));
this.password1 = new FormControl('', Validators.compose([Validators.required, Validators.pattern(mediumRegex)]));
this.password2 = new FormControl('', Validators.compose([Validators.minLength(8), Validators.required, Validators.pattern(mediumRegex)]));
console.log(this.email);
}
matchPassword(AC: AbstractControl): any {
const password1 = AC.get('password1').value; // to get value in input tag
const password2 = AC.get('password2').value; // to get value in input tag
if (password1 !== password2) {
// console.log('false');
AC.get('password2').setErrors({'MatchPassword': true});
// console.log(AC);
// console.log(this.registrationForm);
} else {
// console.log('true');
return null;
}
}
createForm(): void {
this.registrationForm = this.fb.group({
email: this.email,
firstName: this.firstName,
lastName: this.lastName,
password1: this.password1,
password2: this.password2,
}, {
validator: this.matchPassword // your validation method
});
}
答案 0 :(得分:1)
基本上你没有看到所有的验证结果,因为这行
AC.get('password2').setErrors({'MatchPassword': true});
因为你覆盖了表单验证器,所以该行已经摆脱了之前的验证结果,只是放了它的结果。
我之前在类似场景中所做的是定义一个嵌套表单组来包装这些密码控件并仅将自定义验证器函数分配给它。因此,您的表单声明将如下所示:
this.registrationForm = this.fb.group({
email: this.email,
firstName: this.firstName,
lastName: this.lastName,
passwords: this.fb.group({
password1: this.password1,
password2: this.password2
}, {validator: this.matchPassword}) // your validation method})
});
我已经准备好了一个plunker来更好地说明如何达到每个案例的验证错误(只需点击提交以查看结果)https://plnkr.co/edit/94VUlt8K5SvWXBGcW6Qx