Guides
Last Updated Nov 16, 2023

Complete Guide to Validating Emails in Angular

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Email validation has become a critical part of application development in recent years, and is also a crucial aspect of email marketing. In order to make sure that your users are providing you with accurate and valid email addresses when they sign up for your app or for your mailing list, you must verify and validate every email that comes in.

In this article, we’ll look at client side email validation using Angular, a popular frontend Javascript framework. We’ll walk through the implementation of Angular email validation using Angular form validation and HTML validation. We’ll also explore an alternative method for email validation using the AbstractAPI Free Email Validation API, and briefly discuss the differences between Angular and AngularJS.

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

Understanding Email Validation

Email validation is the process of determining whether a given email address is correct, valid, and deliverable. That means everything from making sure there are no typos in the address, to checking MX records for the domain, to making sure the address isn’t a temporary address.

Angular provides some nice out-of-the-box validation solutions using form control and HTML5 input validation that you can easily implement in your app’s frontend to check for typos and malformed strings.

Implementing Angular Email Validation

How does Angular or AngularJS validate email address strings? There are three ways to validate email addresses using Angular:

  • EmailValidator - Angular’s built-in validation tool that checks whether a given string is an email address
  • PatternValidator - Angular’s validation tool that allows you to provide a RegEx pattern to use as a validator
  • CustomValidator - your own custom-built email validator built using ng-model.

Before we look at how to implement each method, let’s touch on template-driven forms vs reactive forms.

Template Driven Forms

Template-driven forms are very similar to what AngularJS provides. A template-driven form uses the two-way data binding of ng-model to sync an HTML form with a data model.

To use template driven forms in Angular, you must import the directive into your root App file:


import {FormsModule} from "@angular/forms";

@Component({...})

export class App { }

@NgModule({

  declarations: [App],

  imports: [BrowserModule, FormsModule],

  bootstrap: [App]

})

export class AppModule {}

Now you can build template-driven forms in your application like so:


<form #myForm="ngForm" (ngSubmit)="onSubmitTemplateBased()">

  <p>

    <label>Email:</label>

      <input type="email" [(ngModel)]="user.email" required placeholder="Your Email">

  </p> 

  <button type="submit">Submit</button> </p>

</form>

The logic for this form (i.e. what happens when the form is interacted with and submitted) is put into an attached component class:


@Component({

  selector: "template-driven-form",

  templateUrl: 'template-driven-form.html'

})

export class TemplateDrivenForm {

  user: Object = {};

  onSubmitTemplateBased() { console.log(user.email); } 

}

Here, you can see that all we’re doing on submit is logging the data from the form. In a real app, this would be where you send your data to the server.

Reactive Forms

Reactive forms are implemented in a very similar way to template-driven forms, but you must import a different module for them:


import {NgModule} from "@angular/core";

import {ReactiveFormsModule} from "@angular/forms";

@Component({...})

export class MyApp { } 

@NgModule({ 

  declarations: [App],

  imports: [BrowserModule, ReactiveFormsModule],

  bootstrap: [App]

})

export class AppModule {}

Now, you can build a reactive form using the following format:


<form [formGroup]="form" (ngSubmit)="onSubmit()">

  <p>

     <label>Email:</label>

      <input type="email" formControlName="email">

  </p>

  <button type="submit">Submit</button>

</form>

As you can see, the difference is that the entire form is bound to a single variable in the data model via the formGroup directive and given a form name. Also, the required attribute has been left off the input - this is because validation will now happen inside the component class:


import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; 

@Component({ selector: "reactive-form", templateUrl: 'reactive-form.html'})

export class ReactiveFormExample {

  form = new FormGroup({ "email": new FormControl("", Validators.required) }); 

  onSubmitModelBased() {

    console.log("reactive form submitted");

    console.log(this.form);

  }

}

Here, we see the validators being applied to the email field of the form variable via a FormControl and we see that the submission of a form is handled by submitting the entire form at once.

For the purposes of this tutorial, we’ll use template-driven forms. For a deep dive into template-driven vs. reactive forms, check out this blog post.

EmailValidator

You can use the EmailValidator module in a template form without even having to handle validation in the component class. All the validation is handled by the form itself:


<form #customForm="ngForm" (ngSubmit)="mySubmit(customForm)">   
   <input type="email" name="email" ngModel #email="ngModel" required email>

    <div class="error" *ngIf="email.touched">
      <p *ngIf="email.errors?.['required']">Email is required</p>
      <p *ngIf="email.errors?.['email']">Not a valid Email</p>
    </div>

    <button type="submit" [disabled]="customForm.invalid">Submit</button>

  </form>

Because we’ve applied the email attribute to the input, Angular will handle all validation of the address to make sure the string matches what Angular expects to be a valid email address and update the email model accordingly.

In the div we can examine the model and show an error message to the user if the model’s error.required or error.email field contains any required or email errors. We've added a class of error to the div so we can use CSS to style the error message appropriately.

The required attribute is similar to AngularJS’s ng-required directive. You could also add minLength and maxLength attributes to validate the length of the input.

Angular will even handle disabling the Submit button for us if the form is invalid (similar to using ng-disabled in AngularJS.) In this example, all that would need to be included in the component class is the mySubmit logic to handle submission.

PatternValidator

Unfortunately, Angular’s email attribute is not 100% reliable at detecting invalid email addresses. For example, it accepts abc.abc as a valid email address.

For a slightly more reliable method, we can use RegEx to do pattern validation (see later paragraphs for why this is still not a great solution.) This is similar to AngularJS’s ng-pattern directive.

Instead of using the email attribute on the input, we’ll instead add a pattern attribute and provide our own custom RegEx string to compare to the email string for validation:


<form #customForm="ngForm" (ngSubmit)="mySubmit(customForm)">   
   <input
      type="email"
      name="email"
      ngModel
      #email="ngModel"
      required
      pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
   >

    <div class="error" *ngIf="email.touched">
      <p *ngIf="email.errors?.['required']">Email is required</p>
      <p *ngIf="email.errors?.['pattern']">Not a valid Email</p>
    </div>

    <button type="submit" [disabled]="customForm.invalid">Submit</button>

  </form>

Angular will now evaluate anything that is typed into the input against the RegEx pattern you provided, and use that to determine whether or not the email is valid.

Custom Validator

A much more robust method for doing email validation is to create your own custom validator in the component class and use that for validation. This way, you can use an external validation API or your own validation code to validate the addresses (we’ll look at how to use AbstractAPI to validate email addresses in a later section.)

To create a custom validator, define it in a separate directive file. In this example, we’ll name our file email-validator.directive.ts.


export function invalidEmailValidator(emailRegEx: RegExp): ValidatorFn {

  return (control: AbstractControl): ValidationErrors | null => {

    const forbidden = emailRegEx.test(control.email);

    return forbidden ? { invalidEmail: {value: control.email}} : null; };

}

This factory accepts a regular expression as an argument and returns a function that uses that regular expression to test the email field of a passed Form Control. It’s a reusable piece of code that can be applied to any email input textbox in your application.


<input type="email" required appInvalidEmail="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" [(ngModel)]="user.email" #name="ngModel">

AngularJS Email Validation

The primary difference between Angular and AngularJS is that Angular is based on Typescript while AngularJS is based on Javascript. Typescript is just a more strongly opinionated form of Javascript that allows you to use static typing and interfaces. Typescript is also a little more readable and more easily maintained than Javascript.

AngularJS email validation is very similar to Angular template-driven validation. There are just a few differences in the names of modules. Here is an example of using the EmailValidator module in AngularJS:

Validation Patterns and RegEx

The problem with using RegEx to validate email addresses is that it is impossible to come up with a regular expression that captures all possible valid or invalid email addresses. These days, especially with unique top-level domains being used everywhere, it becomes very difficult to predict what a valid email address looks like.

For example, the following are all valid email addresses:

user@tyes.media

user@met.museum

user@gmail.com

user@hype.io

In order to allow all those addresses to pass as valid, you would have to write an insanely long RegEx pattern, and you still probably won’t get it right.

The other issue with using RegEx for email validation is that it doesn’t check things like MX records, SMTP, deliverability scores, or whether the email is a role-based email, catch-all email, or temporary address.

A Better Solution: AbstractAPI

Using an email validation API is the only way to ensure not only that the string the user provided you is free from typos or errors, but that the address is valid, deliverable, and active. Let’s quickly walk through how to implement AbstractAPI in your Angular custom validator.

Get an API Key

To use the API, you’ll need an API key. You can sign up for a free account with Abstract using an email and password. Navigate to the Email validation homepage and click ‘Get Started.’

From there, you’ll be taken to the API dashboard where you’ll see your API key and links to documentation, customer support, and pricing.

Copy the API key. You’ll need to use it in your validator.

Create an Async Validator

Using an API to validate your email addresses means you’ll be making a network request, so you’ll need to write a validator that implements the AsyncValidator interface.

First, make the HttpClient module available in your app by importing it into the AppModule and adding it to the imports array:


import { HttpClientModule } from '@angular/common/http';

and


@NgModule({

  imports: [

    HttpClientModule,

  ],

})

Next, create a custom async validator that uses the HttpClient to send a GET request to the AbstractAPI endpoint. You’ll pass the email for validation and your API key as query string parameters.


import { AbstractControl, ValidationErrors } from '@angular/forms' 

import { Observable, of } from 'rxjs';

export function invalidEmail(email, control: AbstractControl): Observable<ValidationErrors> | null {

    const API_KEY = "YOUR_API_KEY";

    const API_URL = "https://emailvalidation.abstractapi.com/v1/
    ? api_key =" + API_KEY + "& domain =" + email;

    const api_response = Observable HttpClient.get(API_URL);    

    if (!api_response.is_valid_format) {

      return of({ 'invalidEmail': true })

    }      

    return of(null)

}

The API will return a JSON response object with data about the email and a boolean field telling you whether it is valid or not.


{
    "email": "eric@abstractapi.com",
    "autocorrect": "",
    "deliverability": "DELIVERABLE",
    "quality_score": 0.80,
    "is_valid_format": true,
    "is_free_email": false
   "is_disposable_email": false
    "is_role_email": false
    "is_catchall_email": true
    "is_mx_found": true
    "is_smtp_valid": true
}

In our validation example, we only looked at the is_valid_format field, but you should examine each of the relevant fields to determine whether or not the provided email is valid.

Common Issues and Solutions

The primary concerns when implementing email validation into your forms is to make sure you are handling errors correctly, displaying relevant error messages to the user, and disabling inputs and buttons if the user has not input a valid address.

Angular can handle a lot of this for you through the errors and disabled fields, but it is your job to make sure the logic is correct for when things are disabled, and the messages you are displaying to users make sense.

Another common issue developers run into is using RegEx patterns that don’t catch all invalid emails, or don’t allow valid emails to pass. This is why you should never rely solely on RegEx for your email validation. RegEx is fine to use as a typo checker, but that should only be one line of defense in your filtering of invalid addresses.

Conclusion

Angular makes email validation quick and simple. When used in combination with an email validation service like AbstractAPI’s Free Email Validation API, it is a powerful way to prevent invalid emails from clogging up your precious email list.

FAQs

How do you validate an email address in Angular?

There are three ways to validate an email address in Angular: using the built-in EmailValidator module, using the built-in PatternValidator module and providing a RegEx pattern, or using the CustomValidator module and writing your own validation function using an API or other email validation service.

What is the difference between Angular and AngularJS in terms of email validation?

The primary difference between Angular and AngularJS is that Angular uses Typescript while AngularJS uses Javascript. That means everything in your Angular app must be strongly typed, and you have access to interfaces and other helpful Typescript things.

Angular also introduced the concept of ‘reactive forms’ which means you can bind your entire form to a data model and pass custom validators directly to the component class for custom validation.

Can you use regex for email validation in Angular?

You can. The question is ‘should you’? And the answer to that is, no. At least, not only RegEx. RegEx is fine for evaluating a string for typos, but it should not be relied upon to perform email validation, as it does not tell you whether MX records are valid, or whether the email address is a catch-all, role-based, or temporary email. Additionally, with the prevalence of custom top-level domains, it would be impossible to write a regular expression that correctly allowed all valid email addresses through.

4.9/5 stars (12 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Email Verification API
API
key now
Verify & validate emails using Abstract's API.
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required