WebMasterCampus
WEB DEVELOPER Resources

Javascript Validate an Email Address

Learn how to Javascript Validate an Email Address using Javascript


Javascript Validate an Email Address

Email validation is very common during web development. Most of the website have contact us page where user can type email address with comment and developer needs to verify it to stop spam.

Email validation using regular expression is the most common and useful way to make sure user have input the valid email address.

Email Validation Example using Regex

function verifyEmail(email) {

var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

return re.test(String(email).toLowerCase());
}

Email Validation Example using Regex (accept unicode):

function verifyEmail(email) {

var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i

return re.test(String(email).toLowerCase());

If you are looking to read more about email Regular Expressions visit whatwg.org

Email Validation Using Regex from W3C

    /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

Email Validation Working Example


  <input id="email" type="email" placeholder="enter your email" />
  <button id="validate" onClick="return validate()">Validate</button>

  <div id="result"></div>

  <script>

    function validateEmail(email) {
      var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return re.test(email);
    }

    function validate() {
      var email = document.getElementById("email").value;

      if (validateEmail(email))
          document.getElementById("result").innerHTML = email + " is valid ";

      else
          document.getElementById("result").innerHTML = email + " is not valid ";

    }

  </script>

Please keep in mind that we should never trust only using JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

Created with love and passion.