gpt4 book ai didi

Angular2 react 形式错误显示

转载 作者:太空狗 更新时间:2023-10-29 17:05:44 24 4
gpt4 key购买 nike

我正在尝试通过制作联系表格来了解 Angular2 的响应式表格。一切正常,但有一个错误似乎给我带来了一些麻烦。当我使用时一切正常浏览器的控制台:预期验证器返回 Promise 或 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'
}
}

}

最佳答案

当你有多个验证规则时,你必须将它们插入一个数组中:

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 ])),
});

关于Angular2 react 形式错误显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com