【问题标题】:How to handle form error validations in angular如何以角度处理表单错误验证
【发布时间】:2018-11-01 09:18:36
【问题描述】:

嗨,我是 Angular 的新手,在我的表单中,我有三个字段 Nameemail
广播部分我的要求是

-->当我选择名称单选按钮时,名称输入字段是必需的

-->当我选择电子邮件单选按钮时,电子邮件输入字段是必需的

我尽力了我的水平但没有结果我该怎么做这个要求有人可以帮助我吗

.html:

<form class="example-form" [formGroup]="emailForm">

    <!-- Name -->
    <mat-form-field class="example-full-width">
        <input matInput placeholder="Name" formControlName="name"
           [errorStateMatcher]="matcher" [(ngModel)]="name" [required]="radioModel=='1'">
             <mat-hint>Errors appear instantly!</mat-hint>
             <mat-error *ngIf="emailForm.get('name').hasError('required')">
               Name is <strong>required</strong>
             </mat-error>
  </mat-form-field>

  <!-- Email -->
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" formControlName="email"
           [errorStateMatcher]="matcher" [(ngModel)]="email" [required]="radioModel=='2'">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailForm.get('email').hasError && !emailForm.get('email').hasError('required')">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailForm.get('email').hasError('required')">
      Email is <strong>required</strong>
    </mat-error>
  </mat-form-field>


<!-- Radio Button -->
<div class="radion-button">
  <mat-radio-group formControlName="radioGroup" [(ngModel)]="radioModel">
  <mat-radio-button value="1">Name</mat-radio-button>
  <mat-radio-button value="2">Email</mat-radio-button>
  <mat-error *ngIf="emailForm.get('radioGroup').hasError('required') && emailForm.get('radioGroup').touched">
               Selection is <strong>required</strong>
             </mat-error>
</mat-radio-group>
</div>
</form>

.ts:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroupDirective, NgForm, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

/** Error when invalid control is dirty, touched, or submitted. */
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));
  }
}

/** @title Input with a custom ErrorStateMatcher */
@Component({
  selector: 'input-error-state-matcher-example',
  templateUrl: './input-error-state-matcher-example.html',
  styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
  emailForm: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {

    //Form Group
    this.emailForm = new FormGroup({
      email:new FormControl('', [Validators.required,Validators.email]),
      name:new FormControl('', [Validators.required]),
      radioGroup:new FormControl('',[Validators.required])
    });
  }
  matcher = new MyErrorStateMatcher();
}

我的代码---->https://stackblitz.com/edit/angular-2m1vdq-yfxnps

【问题讨论】:

标签: angular angular-material angular2-form-validation


【解决方案1】:

如果您从 TS 文件中删除 Validators.required,它应该可以工作

this.emailForm = new FormGroup({
  email:new FormControl('', [Validators.email]),
  name:new FormControl('', []),
  radioGroup:new FormControl('',[Validators.required])
});

Here is a fork of your StackBlitz

【讨论】:

  • 当我触摸字段时显示一个小问题错误消息,但当我选择单选按钮时需要显示错误消息
  • @AbhiRam 在这种情况下,请从 ErrorStateMatcher 中删除 (control.dirty || control.touched || isSubmitted)
  • 非常感谢您的回答很有帮助
【解决方案2】:

您可以根据条件使用 setValidators 向 FormControls 动态添加验证。

this.emailForm.get('radioGroup').valueChanges.subscribe(value=>{
      if(value === '1'){
        this.emailForm.get('name').setValidators(Validators.required);
        this.emailForm.get('name').updateValueAndValidity();
        alert('name is required');
      }else if(value === '2'){
        this.emailForm.get('email').setValidators(Validators.required);
        this.emailForm.get('name').updateValueAndValidity();
        alert('email is required');
      }
    });

https://stackblitz.com/edit/angular-2m1vdq-m5gnzz

【讨论】:

    【解决方案3】:

    您可以使用NPM 包。它简单易用,可针对反应式和模板驱动的表单进行自定义。

    代码sn-p:

    HTML

    <form [formGroup]="demoForm">
        <div>
             <label for="name">Name</label>
             <input type="text" formControlName="name" name="name" placeholder="Name validator">
             <tn-form-error [control]="demoForm.controls.name" [field]="'Name'"></tn-form-error>
        </div>
    </form>
    

    组件

    <p>
     this.demoForm = new FormGroup({
          name: new FormControl(''[Validators.required])
     });
    

    玩转stackblitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多