角度表单验证如何在提交时显示错误消息

时间:2018-09-10 09:23:46

标签: angular forms validation

我的表格如下:

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

现在,我需要在单击“提交”按钮时显示验证消息。现在,如果表单无效,我现在禁用了提交按钮。但是它不会在相应的字段附近显示错误消息,这会使用户认为什么也没有发生。如何触发错误消息以显示在相应的输入字段附近?

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作。

首先删除“提交”按钮中的禁用逻辑。

在组件模板中。

<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类。

答案 1 :(得分:0)

使用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();
        }
    }
}

答案 2 :(得分:0)

保存时,如果表单无效,只需在表单组上调用 markAllAsTouched()

saveDetails() {
  if(!this.editProfileForm.valid) {
    this.editProfileForm.markAllAsTouched();
  }
}