【问题标题】:Angular 6 + Angular Material - Form validation on submitAngular 6 + Angular Material - 提交时的表单验证
【发布时间】:2019-04-08 11:34:27
【问题描述】:

我有一些设置了不同验证规则的输入字段。 但我也想在提交时一次对所有字段添加一些验证,或者禁用提交按钮,如果上面有任何错误。

但是,我并没有从一开始就将所有输入都放在表单标签中,现在我遇到了一些麻烦。我对这一切都很陌生,所以你能帮帮我吗?有没有办法解决它,而无需重新创建所有表单? :(

我已经尝试添加:

  <form #stepOneForm="ngForm">

  <button type="submit [disabled]="!stepOneForm.form.valid" mat-button matStepperNext>Go to next step</button>

但它没有帮助......

我的代码如下:

HTML

      <!-- Name -->
      <mat-form-field class="dcp-input-field">
        <input matInput placeholder="Name" [formControl]="name" [errorStateMatcher]="matcher">
        <mat-hint>Please enter your name</mat-hint>

        <mat-error *ngIf="name.hasError('required')">
          This is <strong>required</strong> field
        </mat-error>
      </mat-form-field>

      <!-- DoB -->
      <mat-form-field class="dcp-input-field">
        <input matInput [matDatepicker]="dp" placeholder="Date of Birth" [formControl]="dob" [errorStateMatcher]="matcher">
        <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
        <mat-datepicker #dp></mat-datepicker>
        <mat-hint>Please enter your date of birth</mat-hint>

        <mat-error *ngIf="dob.hasError('required')">
          This is <strong>required</strong> field
        </mat-error>
      </mat-form-field>

      <!-- PolicyNo -->
      <mat-form-field class="dcp-input-field">
        <input matInput placeholder="Policy number" [formControl]="policyNo" [errorStateMatcher]="matcher">
        <mat-hint>Please enter your Policy number</mat-hint>

        <mat-error *ngIf="policyNo.hasError('required')">
          This is <strong>required</strong> field
        </mat-error>
        <mat-error *ngIf="policyNo.hasError('minlength')">
          The value is <strong>too short</strong>
        </mat-error>
      </mat-form-field>

TS

 export class MyErrorStateMatcher implements ErrorStateMatcher {
   isErrorState(
     control: FormControl | null,
     form: FormGroupDirective | NgForm | null
   ): boolean {
     const isSubmitted = form && form.submitted;
     return !!(
       control &&
       control.invalid &&
       (control.dirty || control.touched || isSubmitted)
     );
   }
 }


  name = new FormControl("", [Validators.required]);
  dob = new FormControl("", [Validators.required]);
  policyNo = new FormControl("", [
    Validators.required,
    Validators.minLength(6)
  ]);

  matcher = new MyErrorStateMatcher();

谢谢你,对不起菜鸟问题! ;)

【问题讨论】:

  • 我也尝试将我所有的 FormControls 插入到一个 FormGroup 中,但是在那之后所有的单一验证都被破坏了,所以看起来我又做错了什么......
  • 您想在材料步进器的多步中使用单个表单并希望在表单有效之前禁用按钮?
  • 实际上,我想要几个表格按步骤划分,是的 - 如果有一些错误,我想禁用“转到下一步”按钮。因此,如果所有步骤都已验证,则无需将验证设置为整体流程。

标签: angular validation angular-material


【解决方案1】:

HTML
将所有输入包装在 form 标签中

而是

<form #stepOneForm="ngForm">

<form (ngSubmit)="onSubmit()" [formGroup]="myForm"></form>

改为

<input matInput placeholder="Name" [formControl]="name" [errorStateMatcher]="matcher">

<input matInput placeholder="Name" formControlName="name">

所有输入 formControlName 不是 [formControl]

改为

<button type="submit [disabled]="!stepOneForm.form.valid" mat-button matStepperNext>Go to next step</button>

<button type="submit" [disabled]="myForm.invalid" mat-button matStepperNext>Go to next step</button>

--当您尝试显示错误消息以访问输入错误验证时
而是

name.hasError('required')

myForm.get('name').errors?.required
//or
myForm.get('name').errors['required']

使用safe navigation operator (?.) 来检查错误的两种方法都将发挥它们之间的主要区别,就像你说“干草角度检查首先是否有错误(不是未定义或未定义)然后检查所需的错误类型,maxLength ...等"主要目的是防止javascript引发错误cannot read property供参考safe navigation operator

或(另一个验证案例)

*ngIf="myForm.get('name').invalid && myForm.get('name').touched"


TS

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...']
})
export class myApp implements OnInit {
  myForm: FormGroup;

  ngOninit() {
    this.myForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'policyNo': new FormControl(null, validators.minLength(5))
      // the rest of inputs with the same approach
    });
  }

  onSubmit() {
    // when submit the form do something
  }
}

您在这里使用 reactive forms 而不是 template driven 每个都有不同的用途,请确保您对两者都使用正确的方式,因为您将 reactive approachtemplate driven approach 搞砸了,这一切都搞砸了。 推荐阅读Reqctive FromsTemplate Forms

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2018-02-20
    • 2016-09-19
    相关资源
    最近更新 更多