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:

  • あいうえお@a.long.domain.example.university
  • one.“more\ long”@example.website.place
  • customer/department@example.com

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

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

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:

Also see:

Further Reading and References

Comments on this entry are closed.