Complete Guide to Validating Emails in Angular

Last Updated Feb 08, 2022
Emma Jagger

Engineer, maker, Google alumna, CMU grad

Table of Contents:

Validating email addresses is very important for businesses. It enables you to separate real clients from fake contacts.  Also, it helps you to prevent fraudulent activities. Besides, validating email IDs allow you to increase your sender reputation. So, your email will not end up in the junk folder of the sender.

If you are using Angular, you can easily implement the email validation feature in your web application. It supports various built-in validators for getting the job done quickly. Also, you can use regex for pattern validation. Besides, you can consider using APIs. But which one is the easiest method? In this complete guide to validating emails in Angular, you will find all the details. Now, let’s dive in.

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

2 Methods of email validation in Angular

There are two main methods for Angular email validation:

  1. Built-in validator: Angular features several built-in email validators, including EmailValidator. You can use them to verify the user-provided email addresses.
  2. Pattern validation: Pattern validation enables you to specify a regular expression (regex). Before performing the email validation in Angular, the regex needs to match the user-provided value.

In this post, you will find the way of validating email addresses using EmailValidator and PatternValidator.

Angular Email validation with EmailValidator

EmailValidator is a built-in email validator directive in Angular. It adds the email validator to controls marked with the email attribute. You can use it to perform the verification effectively.

EmailValidator Angular code example

1. If you are working on a template-driven form, you have to use the email attribute with ngModel in controls, with the below input element.


input name="primaryEmail" [ngModel]="user.primaryEmail" email #prmEmail="ngModel"

You can also use the email attribute in this way:


input name="primaryEmail" [ngModel]="user.primaryEmail" email="true" #prmEmail="ngModel"

Here, you have set the email to “true.”

2. If the email address is not valid, you need to show an error message by using this code:


div *ngIf="prmEmail.errors?.email"
  Primary email address is not valid. /div

3. To enable email validation at runtime, you have to set validateEmail to true.


validateEmail = true;

4. Now, you can use email property binding to set the email property of Step 1 to validateEmail.


input name="primaryEmail" [ngModel]="user.primaryEmail" [email]="validateEmail" #prmEmail="ngModel"

Angular Email Validation with Regex

Pattern Validator allows you to validate email addresses by using a custom regex. It helps you to set your own rules conveniently, like allowing only the company’s email address for verification.

You can use the built-in Angular RequiredValidator and the Pattern Validator directives to verify the email IDs. To use the RequiredValidator directive, you will have to insert the required attribute to the form input controls. After checking whether the control is empty or not, it will return the validation result. To utilize the PatternValidator directive, you will need to add the pattern attribute to the form element controls. It will check if the email address matches your custom regex.

Here is a regex that you can use for Angular email validation:


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

PatternValidator code example




  input type="email"
  required pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$" 
  class="form-control"
  name="primaryEmail" 
  [(ngModel)]="userModel.primaryAddress" /



  input type="email" 
  required pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$"
  class="form-control"
  name="secondaryEmail" 
  [(ngModel)]="userModel.secondaryAddress" /

As you can see, you have to use required and pattern attributes to use the custom regex for validating the email address conveniently.

Angular email validation with reactive form

In Angular reactive forms, the validator functions are included in the form control model of the component class. As a result, when there is a change in the form control value, Angular can call the functions easily.

To perform Angular email validation with reactive forms, you will have to go through these steps:

  • Apply validation conditions to the email form controls via regex
  • Provide visual feedback for the invalid email address
  • Display form's errors object message for form validation

Apply Validation Conditions to the Email Form Controls with Regex

With regex, you can easily specify and apply validation conditions to the email form controls. You just need to follow these steps:

1. First, you have to go to app.component.ts file and import Component, FormGroup, FormControl, and Validators.


//app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

2. Now, you have to specify selector, templateUrl, and styleUrls.


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

3. Then you can utilize Regex to apply validation conditions to the email form controls.


export class AppComponent {
  title = 'email-validation-tutorial';
  userEmails = new FormGroup({
    primaryEmail: new FormControl('',[
    Validators.required,
    
  Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]),
    secondaryEmail: new FormControl('',[
    Validators.required,
    
  Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
  });  
}

`

Overall, the code will look like this:


//app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'email-validation-tutorial';
  userEmails = new FormGroup({
    primaryEmail: new FormControl('',[
    Validators.required,
 
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]),
  secondaryEmail: new FormControl('',[
  Validators.required,

Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
});

Provide Visual Feedback for the Invalid Email Address

Now, it’s time for providing real-time visual feedback to users if the validation fails. For example, if the user provides an incorrect email address, you can display a red border, like this:

You can use .ng-invalid classes to check whether the user-provided email address is accurate or not. How about binding the Bootstrap’s class.is-invalid class to the input elements? You can tie it to the condition that the email fields should be invalid and touched. Also, you can utilize the getter method to get access to the specific form controls.

In the app.component.html file, you will have to include this code:




  input [class.is-invalid] = "userEmails.get('primaryEmail').invalid && userEmails.get('primaryEmail').touched"
  type="email" class="form-control" formControlName="primaryEmail" /



  input [class.is-invalid] = "userEmails.get('secondaryEmail').invalid && userEmails.get('secondaryEmail').touched"
  type="email" class="form-control" formControlName="secondaryEmail" /

Here, you have bound Bootstrap’s class.is-invalid class to the input. Also, you have set a condition specifying that the email fields should be invalid and touched.

Display Error Messages for Form Validation

Finally, you have to display error messages to inform the users about the issues associated with the given email address. Simply follow these steps:

1. In the app.component.ts file, you have to create a getter method that returns a form control.


//app.component.ts

//more code here
export class AppComponent {

  get primEmail(){
    return this.userEmails.get('primaryEmail')
  }
  
  get secondEmail(){
    return this.userEmails.get('secondaryEmail')
  }

//more code here

}

2. Now, you have to go to the app.component.html file. You need to create a div element for displaying the error messages conditionally if the email field is invalid and touched.

Here, you have utilized the *ngIf directive to set a condition to render the div element if the given email address is invalid, touched, or contains a value (primEmail.dirty). Also, you have created an additional div element for creating a separate error message that states the following: “Please provide a valid email address.”

Read: The Top 5 Email Validation & Verification Tools

Summary: Email validation with reactive forms in angular

That’s it! Now, you have learned the way of performing Angular email validation with reactive forms. `Here is the complete code:

Code of app.component.html:



div class="container-fluid"
  form [formGroup]="userEmails"
  
    h3 Please provide your email addresses /h3
    
    div class="form-group"
    label Primary Email: /label
    input [class.is-invalid]="primEmail.invalid && primEmail.touched" type="email" class="form-control"
    formControlName="primaryEmail" /
    
    div *ngIf="(primEmail.invalid && primEmail.touched) || primEmail.dirty"
    small *ngIf="primEmail.errors?.required" class="text-danger">Primary email is required /small
    
    small *ngIf="primEmail.errors?.pattern" class="text-danger">Please provide a valid email address /small
    /div
    /div
    
    div class="form-group"
    label>Secondary Email: /label
    input [class.is-invalid]="secondEmail.invalid && secondEmail.touched" type="email" class="form-control"
    formControlName="secondaryEmail" /
    
    div *ngIf="(secondEmail.invalid && secondEmail.touched) || secondEmail.dirty"
    small *ngIf="secondEmail.errors?.required" class="text-danger">Secondary email is required /small
    small *ngIf="secondEmail.errors?.pattern" class="text-danger">Please provide a valid email address /small
    /div
    /div
  /form
/div

Code of app.component.ts:


//app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  get primEmail(){
    return this.userEmails.get('primaryEmail')
  }
  
  get secondEmail(){
    return this.userEmails.get('secondaryEmail')
  }
  
  title = 'email-validation-tutorial';
  userEmails = new FormGroup({
    primaryEmail: new FormControl('',[
    Validators.required,

Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]),
  secondaryEmail: new FormControl('',[
  Validators.required,
  
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
  });
}

Code of app.module.ts:


//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule //added
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Alternatives to email validation in Angular

Another great way of validating emails in Angular using APIs. They can make the entire process very simple. You can verify email addresses with just a few lines of code.

You can try using Abstract’s Email Validation and Verification API. It is lightweight and super-fast. It allows you to validate email addresses effortlessly.

Read: Best Email Validation and Verification APIs

Let’s verify this email address with Abstract’s Email Validation and Verification API: johnsmith@gmail.com


https://emailvalidation.abstractapi.com/v1/
  ? api_key = YOUR_UNIQUE_API_KEY
  & email = johnsmith@gmail.com

If the request is successful, you will get this JSON response:


{
  "email": "johnsmith@gmail.com",
  "autocorrect": "",
  "is_valid_format": true,
  "is_free_email": true,
  "is_disposable_email": false,
  "is_role_email": false,
  "is_catchall_email": false,
  "is_mx_found": true,
  "is_smtp_valid": true,
  "quality_score": 0.99,
}

Notice that "is_valid_format" is set to true. That means the given email address is correct. Also, you get a variety of useful data, like quality score, email role, SMTP validation, etc.

As you can see, the Abstract’s Email Validation and Verification has made the entire process very simple. It doesn’t require you to write any code from scratch. You just need to get the API key and make a request for verifying the email address. So, you can get the job done instantly.

Wrapping Up

That’s how you validate emails in Angular. You can use the regex with Reactive form to verify user-provided email addresses. However, the easiest way is using an email validation API. It will enable you to perform verification effortlessly.

Verify & validate emails using Abstract's API.

Get started for free
Verify & validate emails using Abstract's API.
Get started