我的目标是将所有验证消息放在组件而不是 html 文件中
我有一个注册页面,下面是字段:
public buildRegisterForm() {
this.userForm = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(3)]],
lastName: ['', [Validators.required, Validators.maxLength(50)]],
emailGroup: this.fb.group({
email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
retypeEmail: ['', Validators.required],
}, { validator: formMatcherValidator('email', 'retypeEmail') }),
passwordGroup: this.fb.group({
password: ['', [Validators.required, strongPasswordValidator()]],
retypePassword: ['', Validators.required],
}, { validator: formMatcherValidator('password', 'retypePassword')}),
});
}
我正在按照这个教程链接来实现我想要的,即将我所有的验证消息放在组件文件而不是 html 文件中。
export const validationMessages = {
'firstName': {
'required': 'Your first name is required.',
'minlength': 'Your first name must be at least 3 characters long.'
},
'lastName': {
'required': 'Your last name is required.',
'minlength': 'Your last name must be less than 50 characters long.'
},
'emailGroup': {
'email': {
'required': 'Your email is required',
'pattern': 'Your login email does not seem to be a valid email address.'
},
'retypeEmail': {
'required': 'Your retype email is required',
'match': 'The email provided do not match.'
},
},
'passwordGroup':{
'password': {
'required': 'Your password is required',
'strongPassword': 'Your password must be between 8 - 15 characters and must contain at least three of the following: upper case letter, lower case letter, number, symbol.'
},
'retypePassword': {
'required': 'Your retype password is required',
'match': 'The password provided do not match.'
}
}
onValueChanged 方法
private onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;
// tslint:disable-next-line:forin
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
let control = form.get(field);
// console.log("control", control.dirty);
console.log("controlEmail", control);
if (control && (control.dirty || control.touched) && control.invalid) {
let messages = validationMessages[field];
// tslint:disable-next-line:forin
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
当我有多个 formBuider Group 或嵌套对象时,此方法不起作用。这个1有什么建议吗?
类似于如何使用嵌套表单组验证反应式表单?