in Javascript

Regular Expression To Validate Email Address

The follow snippet is a function I use to validate email addresses. It is a very simple function which uses a regular expression pattern match to test if a email is of a correct format.

Valid Email Format

A valid format is This takes in a parameter of the email address and then runs a pattern match against the regular expression. If it doesn't find any matches then it will fail the validation and the function will return false, if the match returns true then the email will be of a correct format and the function will return true. ## The Javascript Function To Validate Email

 * Validate email function with regualr expression
 * If email isn't valid then return false
 * @param email
 * @return Boolean
function validateEmail(email){
    var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return emailReg.test(email);

How To Use Javascript Function

The best way to use this will be in an IF statement like below.

     alert("Email is correct format");
} else {
     alert("Email is not correct format return false.");

Creating A Shorter RegEx

With a suggestion from @jVaughn_ we can make the RegEx shorter like this.


Validate Emails In PHP

Along with making sure you validate emails on the client side it is important to also validate on the server side. Here is a PHP Snippet to validate email addresses on the server side.

 * validate email
 function is_valid_email($email)
    return preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email);

Subscribe To The Weekly Newsletter

Get weekly updates to your email