[英]Angular form validation how to show error message on submit
我有一个表格如下:
<form [formGroup]="editProfileForm">
<input type="text" id="name" class="form-control" placeholder="First" formControlName="firstName [(ngModel)]="profileDetails.first_name">
<small class="text-danger" [hidden]="editProfileForm.controls['firstName'].valid || (editProfileForm.controls['firstName'].pristine && !submitted)">First name Required</small>
<input type="text" class="form-control" placeholder="Last" formControlName="lastName" [(ngModel)]="profileDetails.last_name">
<small class="text-danger" [hidden]="editProfileForm.controls['lastName'].valid || (editProfileForm.controls['lastName'].pristine && !submitted)">Last name Required</small>
<button class="save-changes-btn" [disabled]="(!editProfileForm.valid)" (click)="saveDetails();">Save Changes</button>
</form>
并且 editProfile 在组件文件中定义为
this.editProfileForm = this.formBuilder.group({
firstName: [_.get(this.profileDetails, 'first_name', ''), Validators.required],
lastName: [_.get(this.profileDetails, 'last_name', ''), Validators.required],
});
现在我需要在单击提交按钮时显示验证消息。 现在,如果表单无效,我已禁用提交按钮。 但是它不会在相应字段附近显示错误消息,这会使用户认为没有任何事情发生。 如何触发错误消息以在相应的输入字段附近显示?
你可以做这样的事情。
首先删除提交按钮中的禁用逻辑。
在组件模板中。
<form [formGroup]="editProfileForm" (ngSubmit)="onSubmit()">
<div class="form-group block" [ngClass]="{'has-error': submitted && (editProfileForm.controls.firstName.errors)}">
<label>Email</label>
<input type="text" class="form-control" formControlName="firstName">
<p>
<span *ngIf="submitted && editProfileForm.controls.firstName.errors?.required">First name is required</span>
</p>
</div>
// other controls
</form>
在组件类中
public onSubmit(): void {
this.submitted = true;
if(!this.editProfileForm.valid) {
return;
}
// make the submitted variable false when submission is completed.
}
如果需要,您可以删除以下部分。
[ngClass]="{'has-error': submitted && (editProfileForm.controls.firstName.errors)}"
当表单控件无效并提交时,它将向元素添加css类。
使用showValidationMsg()
方法并将表单组作为参数传递给提交按钮方法:
showValidationMsg(formGroup: FormGroup) {
for (const key in formGroup.controls) {
if (formGroup.controls.hasOwnProperty(key)) {
const control: FormControl = <FormControl>formGroup.controls[key];
if (Object.keys(control).includes('controls')) {
const formGroupChild: FormGroup = <FormGroup>formGroup.controls[key];
this.showValidationMsg(formGroupChild);
}
control.markAsTouched();
}
}
}
保存时,如果表单无效,只需在表单组上调用markAllAsTouched()
即可。
saveDetails() {
if(!this.editProfileForm.valid) {
this.editProfileForm.markAllAsTouched();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.