Last month I wrote about regular expressions in Java, today I’ll show you how to use regular expression in JavaScript to validate email address.

Here is the code to validate email address in JavaScript using regular expression.

function validateEmail(elementValue){      
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue); 
 } 

Explanation:

The argument to this method is the email address you want to validate.
In the method body we define a variable (‘emailPattern’) and assign a regular expression to it.

Email format: The regular expression for email is

/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/

To understand the regular expression we will divide it into smaller components:

/^[a-zA-Z0-9._-]+:  Means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods,underscores and hyphens.


@:   There must be a ‘@’ symbol after initial characters.

[a-zA-Z0-9.-]+: After the ‘@’ sign there must be some alpha-numeric characters. It can also contain period (‘.’) and and hyphens(‘-‘).

\.: After the second group of characters there must be a period (‘.’). This is to separate domain and subdomain names.

[a-zA-Z]{2,4}$/: Finally, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed.
{2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; us, tx, org, com, net, wxyz).


On the final line we call test method for our regular expression and pass the email address as input. If the input email address satisfies our regular expression, ‘test’ will return true otherwise it will return false. We return this value to the calling method.

You can call this method whenever you want to validate email address.

If you enjoyed this post, make sure you subscribe to my RSS feed!