[英]Show errors in Angular2 forms if form items empty, but user submit form
我有一個userForm
組,其中包含鍵name
, email
和phone
。 我還有一個onValueChanged
函數,該函數可以訂閱以進行表單更改並驗證數據。
buildForm(): void {
this.userForm = this.fb.group({
'name': ['', [
Validators.required,
]
],
'email': [''],
'phone': ['', Validators.required]
});
this.userForm.valueChanges
.subscribe(data => this.onValueChanged(data));
我也有一個提交按鈕,但是如果用戶不打印任何數據並提交表單,我的錯誤就不會顯示。 我該如何解決?
onSubmit() {
this.submitted = true;
}
這是我的錯誤:
formErrors = {
'name': '',
// ...
};
validationMessages = {
'name': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
// ...
},
// ...
};
}
我的onValueChanged
函數:
onValueChanged(data?: any): void {
if (!this.registrationForm) return;
const form = this.registrationForm;
for (const field in this.formErrors) {
this.formErrors[field] = '';
const control: any = form.controls[field];
if (control && control.dirty && !control.valid) {
const messages: string = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
我在這樣的模板中使用驗證:
<div [ngClass]="formErrors.email ? 'has-danger' : '' ">
<label for="email">Email <span class="text-danger">*</span></label>
<input type="email" formControlName="email" id="email">
<div class="form-control-feedback">{{formErrors.email}}</div>
</div>
您需要在component.html(html或html文件)中編寫ngif
語句。 如下面針對phone
formControl:
<div *ngIf="!phone.valid && (phone.touched || submitted)">Required</div>
添加了phone.touched
,以便僅在用戶觸摸formControl之后才會顯示錯誤。
添加了submitted
,因此僅在用戶嘗試提交表單后才會顯示錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.