Validate Email Id In Angular 2/4/5/8

In this blog, you will learn how to validate an Email Id in Angular 2/4/5/8 using Pattern Validation.

In this blog, we are going to see how to validate an Email id in Angular 2/4/5/8 using Pattern Validation. In this case, I have an email field in an Angular form on which we will use pattern attribute with ngModel.
 
Angular provides the PatternValidator directive that adds pattern validator to any control. We use regex as an attribute value as following.
  1. emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";  
In app.component.html, we will use pattern attribute as below.
  1. <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">  
  2.   <table>  
  3. <tr>  
  4.    <td>Email </td>  
  5.    <td>  
  6.      <input type="email" name="emailId" [ngModel]="user.emailId" [pattern]="emailPattern" #userEmail="ngModel">  
  7.      <div *ngIf="userEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'">   
  8.        <div *ngIf="userEmail.errors.pattern">   
  9.          Email not valid.  
  10.        </div>   
  11.      </div>  
  12.    </td>  
  13.    </tr>             
  14.    <tr>       
  15.    <td colspan="2">  
  16.      <button>Submit</button>  
  17.    </td>  
  18.    </tr>       
  19.   </table>    
  20.  </form>   
 Here is the code for app.component.ts.
  1. import { Component } from '@angular/core';  
  2. import { NgForm } from '@angular/forms';  
  3.   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent {  
  10.       
  11.   emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";  
  12.   
  13.   isValidFormSubmitted = false;  
  14.   
  15.   user = new User();  
  16.   
  17.   onFormSubmit(form: NgForm) {  
  18.     this.isValidFormSubmitted = false;  
  19.   
  20.     if (form.invalid) {  
  21.        return;  
  22.     }  
  23.   
  24.     this.isValidFormSubmitted = true;  
  25.     form.resetForm();  
  26.  }  
  27. }  
  28.   
  29. export class User {  
  30.   emailId ?:string;  
  31. }   
Output
 
 
That's it. You have seen how to validate an Email Id in Angular 2/4/5/8 using Pattern Validator.