我试图通过联系表格来了解Angular2的反应形式。这一切都很好,但有一个错误似乎给我带来了一些麻烦。当我使用Validators.required
时,一切正常,但只要我在其中一个控件上添加Validators.minLength
或其他内容,一切都会混乱,我在浏览器的控制台中收到此错误:Expected validator to return Promise or Observable.
。我环顾四周,但我找不到一个简单的解释/这是我的组成部分:
export class ContactRouteComponent {
contactForm: FormGroup;
reasons = REASONS;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.contactForm = this.fb.group({
name: ['', <any>Validators.required, <any>Validators.minLength(3)],
email: ['', <any>Validators.required],
reason: ['',<any>Validators.required],
message: ['', <any>Validators.required]
});
// AFISEAZA MESAJE EROARE
this.contactForm.valueChanges.subscribe(data => this.onValueChanged(data));
this.onValueChanged();
}
onSubmit() {
console.log(this.prepareContactForm());
this.contactForm.reset();
}
prepareContactForm() {
const formModel = this.contactForm.value;
const contactValues: Contact = {
name: formModel.name as string,
email: formModel.email as string,
reason: formModel.reason as string,
message: formModel.message as string
};
return contactValues;
}
onValueChanged(data?: any) {
if(!this.contactForm) { return; }
const form = this.contactForm;
for(const field in this.formErrors) {
// clear previous messages
this.formErrors[field] = '';
const control = form.get(field);
if(control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for(const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
formErrors = {
'name': '',
'email': '',
'reason': '',
'message': ''
}
validationMessages = {
'name': {
'required': 'Name is required',
'minLength': 'Name has to be...'
},
'email': {
'required': 'Name is required'
},
'reason': {
'required': 'Name is required'
},
'message': {
'required': 'Name is required'
}
}
}
答案 0 :(得分:33)
如果有多个验证规则,则必须将它们插入到数组中:
this.fb.group({
password: ['', [ Validators.required, Validators.minLength(5)] ]
})
更新为Angular v5
没有FormBuilder
的最新实施:
form = new FormGroup({
email: new FormControl('',
Validators.compose([ Validators.minLength(5), Validators.email ])),
});
答案 1 :(得分:5)
在表单构建器中添加多个验证器时,应为验证器使用数组[]
大括号
this.contactForm = this.fb.group({
name: ['',
[Validators.required, Validators.minLength(3)]
],
email: ['', Validators.required],
reason: ['', Validators.required],
message: ['', Validators.required]
});