如何在angular中处理表单错误验证

时间:2018-11-01 09:18:37

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

您好,我是新用户,在我的表单中,我有三个字段名称电子邮件
广播部分,我的要求是

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

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

我尽了最大努力,但没有结果。我该怎么做?有人可以帮助我吗?

.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

3 个答案:

答案 0 :(得分:4)

如果从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

答案 1 :(得分:0)

您可以根据条件使用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

答案 2 :(得分:0)

您可以使用 NPM 包。它简单易用,适用于反应式和模板驱动的表单。

代码片段:

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