How To Validate Email Id In Angular

How To Validate Email Id In Angular

In this article, we will learn how to use Pattern Validation in Angular to validate an Email id. In this instance, we will use the pattern attribute with ngModel on an email field in an Angular form.

Any control can now add a pattern validator thanks to Angular's PatternValidator directive. Regex is used as the following attribute value.

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

We will use the pattern attribute in the app.component.html as shown below.

<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
  <table>
  	<tr>
  	  <td>Email </td>
  	  <td>
  	  	<input type="email" name="emailId" [ngModel]="user.emailId" [pattern]="emailPattern" #userEmail="ngModel">
  	  	<div *ngIf="userEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'">
  	  	  <div *ngIf="userEmail.errors.pattern">
  	  	  	Email not valid.
  	  	  </div>
  	  	</div>
  	  </td>
  	</tr>
  	<tr>
  	  <td colspan="2">
  	  	<button>Submit</button>
  	  </td>
  	</tr>
  </table>
</form>

Now, add the following code under the app.component.ts:

import { Component } from '@angular/core';  
import { NgForm } from '@angular/forms';  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
      
  emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";  
  
  isValidFormSubmitted = false;  
  
  user = new User();  
  
  onFormSubmit(form: NgForm) {  
    this.isValidFormSubmitted = false;  
  
    if (form.invalid) {  
       return;  
    }  
  
    this.isValidFormSubmitted = true;  
    form.resetForm();  
 }  
}  
  
export class User {  
  emailId ?:string;  
}

Now, run the application and look at the output screen like below.

How To Validate Email Id In Angular

Conclusion

In this article, we learned how to use Pattern Validation in Angular to validate an Email id using an example.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post