Home  >  Angular 4

Angular 2/4 Email Validation Example

By Arvind Rai, November 04, 2017
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.

Technologies Used

Find the technologies being used in our example.
1. Angular 4.2.4
2. Angular CLI 1.4.9
3. TypeScript 2.3.3
4. Node.js 6.11.0
5. NPM 3.10.10

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 provides EmailValidator 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: '',
   ------
}); 
We can also add validation at run time as following.
this.userForm.get('secondaryEmail').setValidators(Validators.email); 
Find the code snippet of HTML template.
<input formControlName="primaryEmail">
<input formControlName="secondaryEmail"> 
Now to display validation error message we will create a getter method.
get primaryEmail() {
    return this.userForm.get('primaryEmail');
} 
We can display validation error message as following.
<div *ngIf="primaryEmail.errors?.email">
     Primary Email not valid.
</div> 
In the same way we can display error message for 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" > 
If we want to enable/disable email validation at run time, we can use email property binding. Suppose we have a property in component as following.
validateEmail = true; 
Now use property binding as following.
<input formControlName="primaryEmail" [email]="validateEmail" > 
2. Template-driven form

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"> 
We can display validation error message as following.
<div *ngIf="prmEmail.errors?.email"> 
     Primary Email not valid.
</div> 
We can also use email attribute as following.
<input name="primaryEmail" [ngModel]="user.primaryEmail" email="true" #prmEmail="ngModel"> 
We can enable/disable email validation at run time. Suppose we have a component property.
validateEmail = true; 
Now we can use email property binding as following.
<input name="primaryEmail" [ngModel]="user.primaryEmail" [email]="validateEmail" #prmEmail="ngModel"> 

Email Validation using PatternValidator

Email can be validated using Angular PatternValidator 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}$";
Now use Validators.pattern
userForm = this.formBuilder.group({
    -------
    officialEmail: ['', [Validators.required, Validators.pattern(this.emailPattern)]]
}); 
Find the code snippet in HTML template.
<input formControlName="officialEmail"> 
To display validation error message, we will create getter as following.
get officialEmail() {
    return this.userForm.get('officialEmail');
} 
Now display validation error message.
<div *ngIf="officialEmail.errors"> 
   <div *ngIf="officialEmail.errors.required">
       Official Email required.
   </div> 		   
   <div *ngIf="officialEmail.errors.pattern">
       Official Email not valid.
   </div> 
</div> 
b. Using 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">
2. Template-driven form

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}$"; 
In HTML template, we will use pattern attribute as following.
<input name="officialEmail" [ngModel]="user.officialEmail" required [pattern]="emailPattern" #offEmail="ngModel"> 
Display validation error message as following.
<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.ts
export class User {
    primaryEmail: string;
    secondaryEmail: string;
    officialEmail: string; 
} 
user-service.ts
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);
   }
} 
reactive-form.component.ts
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');
  }    
} 
reactive-form.component.html
<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.ts
import { 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);
     form.resetForm();
  }
} 
template-driven-form.component.html
<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> 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		<app-reactive></app-reactive>
		<app-template></app-template>				
             `
})
export class AppComponent {
} 
styles.css
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}
.error {
    color: red;
}
.success {
    color: green;
} 
app.module.ts
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.
Angular 2/4 Email Validation Example

References

EmailValidator
PatternValidator

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us