Search code examples
javascripthtmlregexemail-validation

How can I validate an email address in JavaScript?


I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?


Solution

  • Using regular expressions is probably the best way of validating an email address in JavaScript. View a bunch of tests on JSFiddle taken from Chromium.

    const validateEmail = (email) => {
      return String(email)
        .toLowerCase()
        .match(
          /^(([^<>()[\]\\.,;:\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,}))$/
        );
    };
    

    The following is an example of a regular expression that accepts unicode.

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

    Keep in mind that one should not rely on JavaScript validation alone, as JavaScript can be easily disabled by the client. Furthermore, it is important to validate on the server side.

    The following snippet of code is an example of JavaScript validating an email address on the client side.

    const validateEmail = (email) => {
      return email.match(
        /^(([^<>()[\]\\.,;:\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,}))$/
      );
    };
    
    const validate = () => {
      const $result = $('#result');
      const email = $('#email').val();
      $result.text('');
    
      if(validateEmail(email)){
        $result.text(email + ' is valid.');
        $result.css('color', 'green');
      } else{
        $result.text(email + ' is invalid.');
        $result.css('color', 'red');
      }
      return false;
    }
    
    $('#email').on('input', validate);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <label for="email">Enter email address</label>
    <input id="email" type="email">
    
    <p id="result"></p>