【问题标题】:Angular form validation how to show error message on submit角度表单验证如何在提交时显示错误消息
【发布时间】:2018-09-10 09:23:45
【问题描述】:

我的表格如下:

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

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

【问题讨论】:

    标签: angular forms validation


    【解决方案1】:

    你可以这样做。

    先去掉提交按钮中的禁用逻辑。

    在组件模板中。

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

    【讨论】:

    • 这个构造editProfileForm.controls.firstName.errors?.required写得不是很好,因为get()方法用于访问表单控件,hasError()方法也用于错误。更好地使用editProfileForm.get('firstName').hasError('required')
    【解决方案2】:

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

    【讨论】:

    • Angular Material 和 FormGroup 非常适合我。谢谢!
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2020-01-22
      相关资源
      最近更新 更多