I am trying to learn about reactive forms of Angular2 by creating a contact form. Everything works well, but there is a bug that seems to give me some trouble. Everything works fine when I use Validators.required
, but as soon as I add Validators.minLength
or anything else in one of the controls, all messed up, and I get this error in the browser console Expected validator to return Promise or Observable.
. I looked around, but I could not find a simple explanation / Here is my component:
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]
});
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) {
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'
}
}
}
source
share