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. This is akin to using a regular expression (regex) to check the email's format. Here is a simple script to do this:
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:
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: