How to show different validation messages for emai

2019-05-24 14:47发布

I am using FormGroup, FormBuilder and Validators class to validate a form in Angular2 app.

This is how I am defining the required validation rules for email and password validation:-

export class LoginComponent implements OnInit {
    loginFormGroup:FormGroup;
    adminLoginmodel = new Admin('', '', '', 'Emailsss','Passwordsss');  

    constructor(
       private route: ActivatedRoute,
       private router: Router,
       private _adminLogin: AdminLoginService,
       fb: FormBuilder
    ){
         this.loginFormGroup = fb.group({
            'email' : [null, Validators.compose([Validators.required, Validators.email])],
            'password': [null, Validators.required]
         });
    }
}

The code Validators.compose([Validators.required, Validators.email]) checks both whether an email field is empty and whether the provided string is valid email.

However, I don't know how to show different validation message in different cases. Say

  1. If email field is empty, I need to display "Please provide an email address"
  2. If provided email is not valid, then I need to display "Provided email is not a valid email".

Here is how I was displaying validation message in my html:-

<div class="input-group input-group-lg" [ngClass]="{'has-error':!loginFormGroup.controls['email'].valid && loginFormGroup.controls['email'].touched}">
   <span class="input-group-addon"><i class="glyphicon glyphicon-user red"></i></span>
   <input type="text" class="form-control" placeholder="Email" id="email" name="email" [formControl]="loginFormGroup.controls['email']" [(ngModel)]="adminLoginmodel.email"/>
</div>
<div class="alert alert-danger" *ngIf="!loginFormGroup.controls['email'].valid">You must add an email.</div>

How can I show different messages in different cases?

1条回答
Animai°情兽
2楼-- · 2019-05-24 15:05
import { Component } from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <input [formControl]="ctrl" />

  <div *ngIf="ctrl.errors?.email">
    Provided email is not a valid email
  </div>

  <div *ngIf="ctrl.errors?.required">
    Please provide an email address
  </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  ctrl = new FormControl(null, Validators.compose([Validators.email, Validators.required]));
}

Live demo

Discussion in the comments proved that the answer to this specific problem is:

<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('email')">Provide a valid email.</div>
<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">Please provide an email address</div>
查看更多
登录 后发表回答