A robust JavaScript regular expression for email addresses

When developing a full-scale web application, generally input validation is done with a combination of client-side and server-side code, maybe using a validation framework. For example, mailcheck.js looks pretty cool, as it can help validate and suggest common email typos by trying to verify if the domain exists.

Sometimes though, you just need a quick and easy way to validate input (in particular email addresses) client-side. I found a pretty robust regular expression at regular-expressions.info. It will match 99.99% (good enough for me) of email addresses out there. They’ve got a detailed explanation of why it’s so difficult to match email addresses if you’re interested. I used their regular expression and made a few tweaks to get it working in Javascript in-browser. Try it out with any email address you like. The code is below.

The code to do this:

<label for="emailTextBox">Email:</label>
<input type="text" style="width:40%;" id="emailTextBox"></input>
<input type="submit" value="Validate Email" id="emailInput" onclick="validate();"/>
<strong><p id="result"></p></strong>
<script>
function validate() {
   var email = document.getElementById("emailTextBox").value;
   var matched = email.match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g);
   if (matched == null)
     document.getElementById("result").innerHTML="Not a valid email address!";
   else
     document.getElementById("result").innerHTML="It's valid: " + matched;

   return true;
}
</script>

Questions and comments always welcome.

Leave a Reply

Your email address will not be published.