Validate Email Address jQuery

Last Updated Jun 22, 2022
Ankit Goyal

Technical Writer and Coder - JS, Node, React, Slack, Evernote, Windows 7/10/11, DAW, Audacity, Skype, Mail Clients, Discord, Imaging Apps

Table of Contents:

Why You Need to Validate Email

Despite the rise of alternate channels like social media, email remains the best channel for marketers - providing a $38 return for every $1 spent.

But email lists are prone to get corrupt quickly; addresses become stale at an alarming rate of 22% each year.
So, you need to validate email addresses in your mailing list to gain maximum ROI on marketing dollars. You can use the simple methods in this post to validate email using jQuery to amp up your email marketing game.

How Invalid Email Addresses in Your Mailing List Hurt Your Business

  • You waste marketing dollars on emails that never reach the target customers because the email ID names are invalid.
  • You get low ROI because of poor open and deliverability rates.
  • Even worse, your sender score takes a hit because of the poor metrics mentioned above. If your sender score gets too low, your mail service provider may even ban you from sending marketing emails on their service.

Why Validate Email Using jQuery

It is a common use case to have a user input his email ID in a web form. We can check if this input is a valid email ID on the server-side, but it is best to do it on the client-side as well. There are several pay-offs of doing so:

  • It optimises performance by reducing server connections.
  • It reduces server load.
  • It makes our apps more reactive and in-tune with modern development practices.

You can find two methods of email validation using jQuery below. We also show a powerful method using the pro-grade email validation Abstract API. The Abstract email validation API takes care of all the nitty-gritty details to provide an end-to-end solution that you can easily plug into your apps.

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

How Email Validation is Done

The first step in email validation is to check if the address matches a valid email ID format.

  • Valid Email Address Syntax Check

We use Regex (regular expressions) to check the format of an email address to make sure it matches the allowed format in the specifications (RFC 5321 and RFC 5322).

A valid email address has the form localpart@domain. Here:

  • The localpart can have 64 characters - The specifications allow a wide range of characters including letters, numbers and many special characters. However, most mail service implementations support a smaller restricted set of characters.
  • We will see various methods of email validation using jQuery for these different supported characters to choose how strict we want to be with our email validation.
  • The domain name part has much tighter guidelines - it has to match the pattern for a valid hostname. A valid hostname comprises several 63-character blocks separated by dots. Each block can only have English letters, numbers, and the hyphen (-) character in it. We refer to this as the LDH (Letters, digits, and hyphen) pattern.

We start with the simplest method to validate email address syntax and build up to more robust and complex solutions.

Email Validation Using jQuery - Simple Method

The rules of email ID syntax vary from one mail service provider to another and can get pretty complex. So, we can be clever and start with a simple hack to clean our mailing list.

The logic for this method is straightforward - we only match with a regex to check if the input email ID has an "@" character in it. Here is the code:


// this is a simple and clever method to validate email address 

var email_val = "";
var regexSimpleEmail = /@/;

$("#submitBtn").on("click",function(){
    email_val = $("input").val();
    if (validateEmail(email_val,regexSimpleEmail)){
        $("#result").addClass("isemail").show().html(`Your email ${email_val} is valid!`);
    }
    else{
        $("#result").removeClass("isemail").show().html(`Sorry, Your email ${email_val} is invalid!`);
    }
});


function validateEmail(email_val,emailRegex){
    if (emailRegex.test(email_val)){
        return true;
    }
    else {
        return false;
    }
}

$("#clear").on("click",function(){
    $("#result").hide().html('')
    $("#inputemail").val("");
})

Here is the related markup file.


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Email Validation </title>
        <script src="jQuery.js" type="text/javascript" ></script>
        <link rel="stylesheet" href="email_validation.css">
    </head>
    <body>
        <div id="main">
            <div>
                <input type="text" name="email_valid_input" id="inputemail" placeholder = "Please enter your email">
            </div>
            <div>
                <p id="result" hidden="true">
                </p>
            </div>
            <div>
                <input type="submit" id ="submitBtn" value="Submit email for verification"/>
            </div>
            <div>
                <input type="submit" id = "clear" value="Clear the form"/>
            </div>
        </div>
        <!-- <script type="text/javascript" src="email_validation.js"></script> -->
        <script src="email_validation_simple.js type="text/javascript" "></script>
    </body>
    </html>

Here is the associated email_validation.css code.


#main {
    position:relative;
    width: 800px;
    height:400px;
    margin: auto;
    top: 200px;
}

body {
    height:100%;
    width:100%;
    background-color: antiquewhite;
}

input {
    margin: 10px;
    border: solid 3px blue;
    background-color: azure;
    border-radius: 20px;
    font-size:2em;
    width: 600px;

}

#submitBtn {
    border: solid 3px violet;
    background-color: bisque;
    margin: 10px;
    border-radius:20px;
    font-size:1.2em;

}

#clear {
    margin:10px;
    border: solid 3px brown;
    background-color: oldlace;
    border-radius:20px;
    font-size:1.2em;
}

p  {
    margin:10px;
    border-radius: 20px;
    font-size:2.2em;
    border: solid 3px red;
    background-color: blanchedalmond;
    color:darkred;

}

.isemail{
    border: solid 3px green;
    background-color: blanchedalmond;
    color:darkgreen;

}

Here is the demo output of this solution.

Simple email validation using jQuery Form
Simple Email Validation - Correct Email Result
Simple Email Validation - Incorrect Email Result

Let's break down the code to see what's going on here.

First up, we prompt the user to input the email they want to validate. Below that, we have a submit button to run the email validation, and a clear button to reset everything. Last, we display the result of the email validation check using jQuery in a paragraph (<p>) element that we initially hide.

In our email_validation_simple.js file, we attach an event handler to the submit button on the click event.
We extract out the user’s input email value and save it in the email_val variable using the .val() method on the input element.

We then run a function by passing in the email_val and regexSimpleEmail arguments with the logic for the email check (more on that a little later). If the user’s input email is valid and the function returns a true value, we display the results paragraph (<p>) element block with a confirmation message that the email is valid. We also add an isemail class to style the output in green and color-code it as a valid email confirmation message.

If the regexSimpleEmail functions returns a false value, we display an invalid email output message. Also, we remove the class we added earlier to color-code it in red as a negative result.

But, as we said, this is a very basic email validation filter for a quick cleaning of your mailing list. So, it does not remove some bad email addresses from your list. A few typical such use cases are:

Simple Email Check - Problem 1

The above email address is not valid as the domain name part does not have a Top-Level Domain (TLD) at the end (TLD's are the ending labels we all know, like .com, .au, or .org). But, our simple email check cannot filter it out.

Simple Email Validation - Problem 2

The above email ID has an incorrect local name part (before the @ sign) as it has many special characters that most email implementations do not support. But, our simple email filter does not catch these.

So, we need to do better and build a more robust function.

Email Validation Using jQuery - Robust Method

Most email service providers support the following formats of valid emails.

The Local Part :

  • May have all the letters of the Latin alphabet in both uppercase and lowercase i.e A-Z and a-z.
  • May have any digit from 0-9.
  • May have these special symbols : -, ., +, and _
  • May have any of the above repeated any number of times.

The Domain Name Part:

  • May have letters, both uppercase or lowercase i.e. A-Z and a-z
  • May have digits from 0-9
  • May have the dash character (-).
  • It may have 4 "labels" that combine characters from the above three sets.
  • The last "label" is special - we call it the Top Level Domain (TLD). It may only have 2 to 4 symbols of the supported character sets.

We devise a regex to match the above pattern and embed it in our code. Here is the JavaScript file for this jQuery validation method. (We use the same HTML and CSS files as before.)


// this script validates email syntax
console.log("connected");

let email_val;
let emailRegex = /^([a-zA-Z0-9_\.\+\-])+\@(([a-zA-z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;


    $("#submitBtn").on("click",function(){
        email_val = $("#inputemail").val();
                if (validateEmail(email_val)){
                $("#result").addClass("isemail").show().html(`Your email ${email_val} is a valid email.`);
            }
        else {
            $("#result").removeClass("isemail").show().html(`Your email ${email_val} is invalid`);
            return false;
        }
    });
    
    function validateEmail(email_val){
        if (emailRegex.test(email_val)){
            return true;
        }
        else
        {
            return false;
        }
    }

$("#clear").on("click", function(){
    $("#result").hide().html('');
    $("#inputemail").val("");
})

Let us break down the regex in this code.

^([a-zA-Z0-9) matches for letters and digits. The ^ sign upfront means the email ID has to begin with this pattern.

We then also match for the special characters allowed in the local part. So, we add -/./+/_ to our regex. Here, we use the backslash (/) before these symbols to escape their usual meaning inside a regex (these carry special meanings inside a regex). So, now the code treats them just like normal dots, dashes, pluses, etc.

We then put a trailing + sign. This means the local part can repeat the above characters many times.

We then put the @ sign. We then add the pattern for a valid "label" inside the domain part of the email ID.

We then have a dot to separate the different labels. The trailing + sign allows us to repeat this pattern multiple times.

Last, we write the regex part for the TLD. It has the same character set as any other label, but we add {2,4} at the end to ensure that it is only between 2 and 4 characters long.

Let us look at the output for different input emails.

Robust Regex to Validate Email Using jQuery
Robust Regex For Email Validation - It supports Special Characters in the Local Part of the Email ID

The regex passes email addresses with allowed special characters as valid.

Our Pattern Matches Multiple Labels in the Domain Part of the Email ID

Our regex allows email IDs with multiple labels in the domain part as valid addresses.

Email IDs with Both Special Symbols and Mutliple Labels are Valid

Now, let us see how our regex catches invalid email addresses.

The TLD (the last label in the domain part) cannot be more than 4 characters long.

We see above that the TLD is longer than 4 characters. So, our regex catches it and throws up a warning.

Special Symbols other than the ones supported make an email address

We use the disallowed special symbols %, $, and ! in our email address above. So, our regex catches them and throws an alert.

Other Steps in Validating Email Addresses

Besides its syntax, we also need to ensure if the email address exists and is active. For this, we need to query the domain server for the correct MX records (for existence) and proper SMTP settings (for configuration).

Writing a jQuery script from scratch for all the above functionality is a bit complex. So, it is best to use an off-the-shelf easy-to-use email validation API service for this.

Here is the code to use the Abstract API for email validation.


// we use abstract API to validate email here
$(document).ready(function(){
    let email_val;
    $("#submitBtn").on("click",function(){
        email_val = $("#inputemail").val();
        $.getJSON(`https://emailvalidation.abstractapi.com/v1/?api_key=<ur_unique_api_key_here>&email=${email_val}`, 
        function(data) {

        if (data.is_valid_format.value){
            $("#result").addClass("isemail").show().html(`Your email ${email_val} has a valid format. <br>`);
        }
        else {
            $("#result").removeClass("isemail").show().html(`Your email ${email_val} is invalid`);
         }
        if ((data.is_mx_found.value) && (data.is_smtp_valid.value)){
            $("#result").append(`<br>Your email ${email_val} exists and is active.`);
         }
         else {
            $("#result").removeClass("isemail").show().html(`Your email ${email_val} is invalid`);
         }
    })
    })
    $("#clear").on("click", function(){
        $("#result").hide().html('');
        $("#inputemail").val("");
    })
    
});

We send a request to the Abstract email validation API with a single line in the $.getJSON() function. We append our unique API key (you can get this when you register for an Abstract API) and the input email ID at the end.

The Abstract API auto-checks the format and the existence of the email address and returns the data as a JSON object.

We check if the key fields of is_valid_format, is_mx_found, and is_smtp_valid are true to mark an email valid.

Let us look at a few demo output cases.

Abstract API checks for valid email IDs accurately
Abstract API matches correctly for allowed special characters in email ID

We see above the Abstract email validation API correctly passes email addresses with allowed special characters as valid email IDs.

The Abstract API filters out email addresses with invalid formats.

The Abstract email validation API filters out an email address with a wrong format with a warning alert.

The Abstract API catches an email with disallowed special characters as invalid
An email ID with an incorrect TLD - the Abstract API warns us with an invaild email alert

We see the Abstract API catches email addresses with disallowed special symbols and wrong TLD labels (longer than 4 characters).

Email validation is common functionality that developers need in apps. You can now use the different methods in our post to embed email validation in your apps easily!

FAQs

Why do I need to validate email addresses on my mailing list?

Invalid email addresses lead to poor deliverability and open rates. So, you waste dollars spent on email marketing. Also, your sender score drops, and if it gets too low, your email service provider may even ban you from sending out marketing emails.

How does email validation work?

Email validation starts by first checking if the email ID has the correct format. You should use regex patterns for this. Then, you need to confirm if the address exists and is active. You need to query the DNS server, look up MX records and check the SMTP configuration for this. This step can get complex. So, it is best to use an out-of-box email validation API service like the Abstract API for this.

How should I validate email addresses?

Email validation using jQuery is a great way to validate email addresses quickly. You can easily create regex patterns and match email IDs against them in jQuery. But, it is tough to write a DIY script to check if an address exists and is valid. So, you should use the Abstract email validation API for an end-to-end solution to validate email IDs in your list.

Validate email instantly using Abstract's email verification API.

Get started for free
Validate email instantly using Abstract's email verification API.
Get started