How to do email validation in jQuery

Last Updated Jan 25, 2021

When a web page contains forms, it is essential to validate the content of each field. Validation must be done on the server-side to ensure that the data is compliant before saving it to a database or passing it to other scripts.

It is also interesting to perform another validation on the client-side using jQuery to save server resources, reduce the number of connections, and make your web application more reactive.

While most of the validations are quite simple, such as checking the presence or the length of a value, some require more effort. This is the case, for example, for email address validation.

How to validate an email address in jQuery?

The validation of an email address in jQuery can be done in two steps. The first one consists of validating its format, and the second one in verifying its existence.

The validation of the format is a straightforward process. The standards that define the allowed formats for an email address are quite permissive, and many special cases quickly make a validation script too complex to write. For example, even if few developers know it, it is possible to have Unicode characters and spaces in an email address.

In this case, it could be enough to check for an "at" sign's presence without any further checking. Here is a simple script to do this:


// Get email address from the input field
var userinput = $(this).val();

// Check if the address contains an "at" sign
var pattern = /@/;
if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}​

For the second step, and especially when the email address is used to send prospecting emails or confirm access to resources, it is essential to verify that it exists. There are several methods to do so, and we will cover two of them in this article.

Method 1: DIY email address verification in jQuery

The safest strategy is to verify the email address's domain name, which is the part after the "at" sign, currently exist. Then, to check that the domain name contains MX fields records and a correct SMTP configuration. The most advanced verifiers will go so far as to indicate whether a disposable address service hosts the email address provided.

To set up such a service by yourself, you will have to write a script able to query a DNS server, analyze its records, and check the correct SMTP configuration.

Firstly, you need to query an API providing information about DNS records of the email address domain. Here is an example using WhoisXmlApi to retrieve MX server addresses from a domain name:


// Get email address from the input field, extract the domain name
var email = $(this).val();
var domain_name = email.replace(/.*@/, "");

// Get MX records from the domain
var whoisxmlapi_api_key = "get_a_key_from_whoisxmlapi.com";
var url = "https://www.whoisxmlapi.com/whoisserver/DNSService?apiKey=" + whoisxmlapi_api_key;
url = url + "&domainName=" + domain_name + "&type=MX&outputFormat=json"
$.getJSON(url, function(data) {
  // Get a list of SMTP servers from the DNS entries
  var smtp_servers = $.map(data.DNSData.dnsRecords, (d) => d.additionalName);
});
Then you have to check that at least one of these servers answer correctly. Unfortunately, in jQuery, there is no function to ping a server, so you will have to make an AJAX request and wait to see if the server responds:

function ping_server(server_address) {
  $.ajax({
    url: server_address,
    success: function() {
      alert('up and running');
    },
    error: function() {
      alert('timeout');
    }
  });
}

Obviously, waiting for a server to respond is not a good practice, especially for a script that runs on the visitor's browser. The visitor may lose patience and abandon what he was doing on your page.

Method 2: easily validate an email address in jQuery

To avoid laborious implementation and time-consuming maintenance, the smart solution is to use Abstract Email Validator, a free and fast service that checks whether an email address is correctly formatted and whether its SMTP servers exist. The icing on the cake, the API also informs about the type of service hosting the address.

After creating your account on Abstract, you will get your private API key. Here's how to use it:


// Get email address from the input field
var email = $(this).val();

// Check email for validite and existence
var abstract_api_key = "get_a_key_from_abstractapi.com";
url = "https://emailvalidation.abstractapi.com/v1/?api_key=" + abstract_api_key;
url = url + "&email=" + email address;
$.getJSON(email, function(data) {
  // Is the email format valid?
  console.log(data.is_valid_format.value);

  // Are there MX records?
  console.log(data.is_mx_found.value);

  // Is the SMTP configuration valid?
  console.log(data.is_smtp_valid.value);

  // Is it hosted on a disposable email service?
  console.log(data.is_disposable_email.value);
})

Related articles