Email Validation in Angular with Example

Email Validation in Angular with Example

In this article we’ll see email validation in Angular. In Angular we can validate Email using two directives EmailValidator and PatternValidator. These two directives are built-in Angular directives for email validation. We can also create our CustomValidator for email validation in Angular.

so there are are 3 ways to Validate Emails in Angular.

3 Ways for Email Validation in Angular

  1. EmailValidator: Angular provides this built-in validator to check whether the email is valid or not in angular.
  2. PatternValidator: PatternValidator in Angular allows you to specify a regular expression (regex) to validate email in Angular.
  3. CustomValidator: You can create your custom validator in Angular to validate email.

We’ll see all these 3 methods for email validation in Angular with example.

Angular Email validation with EmailValidator

Angular supports two types of Form.

  1. Reactive Forms
  2. Template Driven Forms

We’ll see email validation with EmailValidator for both of the form type.

1. EmailValidator in Reactive Form

For, Reactive Forms, we need to import ReactiveFormsModule in app.module.ts

//app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
  imports: [
    //other imports here
    ReactiveFormsModule
  ],
//more code here
})
export class AppModule { }

And in components we’ll use Validators.email with FormGroup.

so we’ll specify Validators.email for specific form control as shown in below:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
 profileForm= this.formBuilder.group({
   firstName: [''],
   lastName: [''],
   email: ['', Validators.email]

 }); 

}

and in component file we can show email formcontrol as following:

<!--app.component.html-->
<div class="container-fluid">
<form [formGroup]="profileForm">

  <div class="form-group">
	<label>First Name:</label>
	<input type="text" class="form-control" formControlName="firstName" />
  </div>

  <div class="form-group">
	<label>LastName:</label>
	<input type="text" class="form-control" formControlName="lastName" />
  </div>

  <div class="form-group">
	<label>Email:</label>
	<input type="email" class="form-control" formControlName="email" />
  </div>
<div *ngIf="(profileForm.get('email').invalid && profileForm.get('email').touched) || profileForm.get('email').dirty">
    	<small *ngIf="profileForm.get('email').errors?.email" class="text-danger">Please enter valid email address</small>
  	</div>

</form>

</div>

We can visualize error of email validation to the client using the following code as showing in above code:

<div *ngIf="(profileForm.get('email').invalid && profileForm.get('email').touched) || profileForm.get('email').dirty">
    	<small *ngIf="profileForm.get('email').errors?.email" class="text-danger">Please enter valid email address</small>
  	</div>

You can also add email validator at run time using the following code:

this.profileForm.get('email').setValidators(Validators.email); 

2. EmailValidator in Template Driven Form

In Template-driven form we need to use email attribute with ngModel in controls.

See the following code for example

<input name="email" [ngModel]="user.email" email #userEmail="ngModel"> 

To show the error to user, use the following code

<div *ngIf="userEmail.errors?.email"> 
     Please enter valid email address
</div> 

We can also use email attribute as following.

<input name="email" [ngModel]="user.email" email="true" #userEmail="ngModel"> 

Here you can see we have passed true to email attribute. we can also pass variable there to on/off email validation at run time.

For i.e

<input name="email" [ngModel]="user.email" [email]="validateEmail" #userEmail="ngModel"> 

and we can declare the validateEmail property in component file.

validateEmail = true; 

Email Validation using PatternValidator

In Angular PatternValidator directive can be use to validate email by passing regex.

If regex pattern won’t match, we will get validation error.

For PatternValidator we need to use pattern attribute with ngModel, formControl, formControlName.

We need to use <strong>Validators.pattern</strong> while creating FormGroup and pass regex for email validation. Now we will provide email validation for Template-driven form as well as Reactive form using Angular PatternValidator directive.

1. PatternValidator with Reactive form

We will use Validators.pattern while creating FormGroup.

For example:

//app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
 profileForm= this.formBuilder.group({
   firstName: [''],
   lastName: [''],
   email: new FormControl('',[Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
 }); 

}

and code snippet in HTML template will be as following.

<!--app.component.html-->
<div class="container-fluid">
<form [formGroup]="profileForm">

  <div class="form-group">
	<label>First Name:</label>
	<input type="text" class="form-control" formControlName="firstName" />
  </div>

  <div class="form-group">
	<label>LastName:</label>
	<input type="text" class="form-control" formControlName="lastName" />
  </div>

  <div class="form-group">
	<label>Email:</label>
	<input type="email" class="form-control" formControlName="email" />
  </div>
<div *ngIf="(profileForm.get('email').invalid && profileForm.get('email').touched) || profileForm.get('email').dirty">
    	<small *ngIf="profileForm.get('email').errors?.pattern" class="text-danger">Please enter valid email address</small>
  	</div>

</form>

</div>

2. Template-driven form

In Template-driven form, we need to use pattern attribute with <strong>ngModel</strong>.

in component file, define the emailPattern variable as following:

emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; 

and in HTML template, we will use pattern attribute as following.

<input name="email" [ngModel]="user.email" required [pattern]="emailPattern" #userEmail="ngModel"> 

To Display validation error message we will use following code.

<div *ngIf="userEmail.errors"> 
   <div *ngIf="userEmail.errors.required"> 
       Email is required.
   </div>			   
   <div *ngIf="userEmail.errors.pattern"> 
       Please enter valid email address.
   </div>	
</div> 

That’s it for email validation in Angular, I hope you like this article

Read also