Angular 6 + Angular Material - 提交时的表单验证

标签 angular validation angular-material

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

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

我试过添加:

  <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();

谢谢您,很抱歉提出新手问题! ;)

最佳答案

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)表单而不是模板驱动每个都有不同的用途确保你对两者都使用正确的方式因为你弄乱了响应式(Reactive)方法 使用 模板驱动方法 搞砸了一切。 推荐阅读Reqctive Froms Template Forms

关于Angular 6 + Angular Material - 提交时的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53148796/

相关文章:

cakephp - 如何在默认位置的其他位置显示CakePHP输入验证错误?

wpf DelegateCommand 和 ValidationRules

angular - 如何理解码件的 Angular Material 主题中使用了哪些颜色?

angular - Angular2 是否有等同于 $document

Angular - 如何在使用 APP_INITIALIZER 加载应用程序时显示等待指示器

Angular - 电子邮件验证不起作用

typescript - 如何隐藏和替换 Angular2 中的组件

javascript - 即使 javascript 表单验证失败,表单也会提交

css - 如何摆脱 Angular Material 芯片上 100% 的水平宽度?

css - Angular 中带有 mat-table 的 float 水平滚动条