HTML.form.guide

How to validate an email address using JavaScript

Validating email address using regular expressions is tricky and is often not recommended. The reason is simple. A valid email address as defined by RFC 2822 can be quite complex.

A valid email is of the format: name@domain

The name can be a set of ‘atoms’ separated by dots. In its simplest form like this: john.doe@domain

now, the atoms can contain

  1. alpha-numeric characters
  2. Any of these characters ! $ & * - = \^ ` | ~ # % ‘ + / ? _ { }
  3. single or double quotes and any character inside the quotes

Now, to the domain part. Most email validation checks assumes that the top level domain can have up to 4 characters. It is not true. There are TLDs like this: .MUSEUM .travel, .international or even .vermögensberatung

For example all the following email addresses are valid:

Writing a email validation that validates for all those cases is difficult but possible. Here is an email suggested from this post:

A near perfect Javascript Email validation regex

function validateEmail(email) 
{
  var re = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;

  return re.test(email);
}

Source

The purpose of the validation

The sad truth is that despite the complex regular expression validation, the email may not be existing, so can still be invalid for practical purposes. You have just validated the format - not its existence.

The only way to truly validate the email address is to send an email to that address and request the user to confirm by clicking on a unique link (or entering a confirmation code)

Remember, if the user’s intention is to enter an invalid email address, she can do it so easily whether you have the most tough validation or not.

The whole purpose of the Javascript email validation should be to check for any unintentional error (like entering name instead of email).

A simple, practical Javascript email validation

The simple, future proof email validation test would be to check the presence of @ symbol

function validateEmail(email) 
{
    var re = /\\S+@\\S+/;
    return re.test(email);
}

Just use HTML5 email input field

This would be the easiest and best option at the moment. Make use of the HTML5 email input element like this:

<input type='email' name='email' placeholder='Your primary email address'/>

Also see:

Further Reading and References