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.
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.
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.
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: