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.
- emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
In app.component.html, we will use pattern attribute as 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>
Here is the code for 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;
- }
Output
That's it. You have seen how to validate an Email Id in Angular 2/4/5/8 using Pattern Validator.