Angular Email Validation Example
March 05, 2020
This page will walk through Angular Email validation example. We can validate email using EmailValidator
and PatternValidator
directive. EmailValidator
provides in-built email validation. PatternValidator
uses regex to validate email. So we can use PatternValidator
for custom email validation. For EmailValidator
we need to use email
attribute in controls such as text input and use Validators.email
in FormControl
while creating FormGroup
. For PatternValidator
we need to use pattern
attribute in controls such as input text and use Validators.pattern
in FormControl
while creating FormGroup
.
Angular 4 uses
novalidate
attribute by default in its form element at run time and hence while submitting form, HTML 5 validation will not work. If we are using Angular 2, we need to write novalidate
attribute in our form element to use Angular form validation. In Angular 4 template-driven form we can use ngNoForm
to enable HTML 5 validation. Here in our example we will provide demo for Template-driven form as well as Reactive form for Angular email validation. Now find the complete example step by step.
Contents
Technologies Used
Find the technologies being used in our example.1. Angular 9.0.2
2. Angular CLI 9.0.3
3. Node.js 12.5.0
Project Structure
Find the project structure of our demo application.angular-demo | |--src | | | |--app | | | | | |--user.ts | | |--user-service.ts | | |--reactive-form.component.ts | | |--reactive-form.component.html | | |--template-driven-form.component.ts | | |--template-driven-form.component.html | | | | | |--app.component.ts | | |--app.module.ts | | | |--main.ts | |--index.html | |--styles.css | |--node_modules |--package.json
Email Validation using EmailValidator
Angular providesEmailValidator
directive to validate email. We need to add email
attribute in controls such as text input and use Validators.email
in FormControl
while creating FormGroup
. We will provide how to validate email with EmailValidator
using Reactive form and Template-driven form.
1. Reactive form
a. Using
Validators.email
with FormGroup
:
We need to use
Validators.email
for email validation while creating FormGroup
.
userForm = this.formBuilder.group({ primaryEmail: ['', Validators.email], secondaryEmail: '', ------ });
this.userForm.get('secondaryEmail').setValidators(Validators.email);
<input formControlName="primaryEmail"> <input formControlName="secondaryEmail">
get primaryEmail() { return this.userForm.get('primaryEmail'); }
<div *ngIf="primaryEmail.errors?.email"> Primary Email not valid. </div>
secondaryEmail
.
b. Using
email
attribute with formControlName
:
We can also validate email using
email
attribute with formControlName
.
<input formControlName="primaryEmail" email > <input formControlName="primaryEmail" email="true" >
validateEmail = true;
<input formControlName="primaryEmail" [email]="validateEmail" >
In Template-driven form we need to use
email
attribute with ngModel
in controls. Find the sample code.
<input name="primaryEmail" [ngModel]="user.primaryEmail" email #prmEmail="ngModel">
<div *ngIf="prmEmail.errors?.email"> Primary Email not valid. </div>
email
attribute as following.
<input name="primaryEmail" [ngModel]="user.primaryEmail" email="true" #prmEmail="ngModel">
validateEmail = true;
<input name="primaryEmail" [ngModel]="user.primaryEmail" [email]="validateEmail" #prmEmail="ngModel">
Email Validation using PatternValidator
Email can be validated using AngularPatternValidator
directive with a regex. If pattern does not match, we will get validation error. In this way we can define custom email validation. For PatternValidator
we need to use pattern
attribute with ngModel
, formControl
, formControlName
. We need to use Validators.pattern
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. Reactive form
a. Using
Validators.pattern
with FormGroup
:
We will use
Validators.pattern
while creating FormGroup
. Find the regex for email.
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
Validators.pattern
userForm = this.formBuilder.group({ ------- officialEmail: ['', [Validators.required, Validators.pattern(this.emailPattern)]] });
<input formControlName="officialEmail">
get officialEmail() { return this.userForm.get('officialEmail'); }
<div *ngIf="officialEmail.errors"> <div *ngIf="officialEmail.errors.required"> Official Email required. </div> <div *ngIf="officialEmail.errors.pattern"> Official Email not valid. </div> </div>
pattern
attribute with formControlName
:
Pattern validation can also be used with
formControlName
with pattern
attribute. Find the code snippet.
<input formControlName="officialEmail" required [pattern]="emailPattern">
In Template-driven form, we need to use
pattern
attribute with ngModel
. Suppose we have a component property that is defining regex as following.
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
pattern
attribute as following.
<input name="officialEmail" [ngModel]="user.officialEmail" required [pattern]="emailPattern" #offEmail="ngModel">
<div *ngIf="offEmail.errors"> <div *ngIf="offEmail.errors.required"> Official Email required. </div> <div *ngIf="offEmail.errors.pattern"> Official Email not valid. </div> </div>
Example-1: Reactive Form Email Validation
user.tsexport class User { primaryEmail: string; secondaryEmail: string; officialEmail: string; }
import { Injectable } from '@angular/core'; import { User } from './user'; @Injectable() export class UserService { createUser(user: User) { console.log('Primary Email: ' + user.primaryEmail); console.log('Secondary Email: ' + user.secondaryEmail); console.log('Official Email: ' + user.officialEmail); } }
import { Component, OnInit } from '@angular/core'; import { FormControl, FormBuilder, Validators } from '@angular/forms'; import { UserService } from './user-service'; import { User } from './user'; @Component({ selector: 'app-reactive', templateUrl: './reactive-form.component.html' }) export class ReactiveFormComponent implements OnInit { isValidFormSubmitted = null; emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; userForm = this.formBuilder.group({ primaryEmail: ['', Validators.email], secondaryEmail: '', officialEmail: ['', [Validators.required, Validators.pattern(this.emailPattern)]] }); user = new User(); constructor(private formBuilder:FormBuilder, private userService: UserService) { } ngOnInit() { this.userForm.get('secondaryEmail').setValidators(Validators.email); } onFormSubmit() { this.isValidFormSubmitted = false; if (this.userForm.invalid) { return; } this.isValidFormSubmitted = true; this.user = this.userForm.value; this.userService.createUser(this.user); this.userForm.reset(); } get primaryEmail() { return this.userForm.get('primaryEmail'); } get secondaryEmail() { return this.userForm.get('secondaryEmail'); } get officialEmail() { return this.userForm.get('officialEmail'); } }
<h3>Template-driven Form</h3> <p *ngIf="isValidFormSubmitted" [ngClass] = "'success'"> Form submitted successfully. </p> <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)"> <table> <tr> <td>Primary Email:</td> <td> <input name="primaryEmail" [ngModel]="user.primaryEmail" email #prmEmail="ngModel"> <div *ngIf="prmEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="prmEmail.errors.email"> Primary Email not valid. </div> </div> </td> </tr> <tr> <td>Secondary Email:</td> <td> <input name="secondaryEmail" [ngModel]="user.secondaryEmail" [email]="validateEmail" #secEmail="ngModel"> <div *ngIf="secEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="secEmail.errors.email"> Secondary Email not valid. </div> </div> </td> </tr> <tr> <td>Official Email:</td> <td> <input name="officialEmail" [ngModel]="user.officialEmail" required [pattern]="emailPattern" #offEmail="ngModel"> <div *ngIf="offEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="offEmail.errors.required"> Official Email required. </div> <div *ngIf="offEmail.errors.pattern"> Official Email not valid. </div> </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
Example-2: Template-driven Form Email Validation
template-driven-form.component.tsimport { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { UserService } from './user-service'; import { User } from './user'; @Component({ selector: 'app-template', templateUrl: './template-driven-form.component.html' }) export class TemplateDrivenFormComponent implements OnInit { isValidFormSubmitted = false; validateEmail = true; emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; user = new User(); constructor(private userService: UserService) { } ngOnInit() { } onFormSubmit(form: NgForm) { this.isValidFormSubmitted = false; if (form.invalid) { return; } this.isValidFormSubmitted = true; this.user = form.value; this.userService.createUser(this.user); this.user = new User(); form.resetForm(); } }
<h3>Template-driven Form</h3> <p *ngIf="isValidFormSubmitted" [ngClass] = "'success'"> Form submitted successfully. </p> <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)"> <table> <tr> <td>Primary Email:</td> <td> <input name="primaryEmail" [ngModel]="user.primaryEmail" email #prmEmail="ngModel"> <div *ngIf="prmEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="prmEmail.errors.email"> Primary Email not valid. </div> </div> </td> </tr> <tr> <td>Secondary Email:</td> <td> <input name="secondaryEmail" [ngModel]="user.secondaryEmail" [email]="validateEmail" #secEmail="ngModel"> <div *ngIf="secEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="secEmail.errors.email"> Secondary Email not valid. </div> </div> </td> </tr> <tr> <td>Official Email:</td> <td> <input name="officialEmail" [ngModel]="user.officialEmail" required [pattern]="emailPattern" #offEmail="ngModel"> <div *ngIf="offEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="offEmail.errors.required"> Official Email required. </div> <div *ngIf="offEmail.errors.pattern"> Official Email not valid. </div> </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-reactive></app-reactive> <app-template></app-template> ` }) export class AppComponent { }
table { border-collapse: collapse; } table, th, td { border: 1px solid black; } .error { color: red; } .success { color: green; }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ReactiveFormComponent } from './reactive-form.component'; import { TemplateDrivenFormComponent } from './template-driven-form.component'; import { UserService } from './user-service'; @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], declarations: [ AppComponent, ReactiveFormComponent, TemplateDrivenFormComponent ], providers: [ UserService ], bootstrap: [ AppComponent ] }) export class AppModule { }
Run Application
To run the application, find following steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your angular CLI application. To install angular CLI, find the link.
3. Run ng serve using command prompt.
4. Now access the URL http://localhost:4200
When we click on submit button, we will get following output.

References
EmailValidatorPatternValidator