How to validate an email address in JavaScript ?

How to validate an email address in JavaScript ?

Asked on December 14, 2018 in Regex.
Add Comment


  • 3 Answer(s)

    The best solution is:

    Applying regular expressions is probably the rigthy way.

    function validateEmail(email) {
      var re = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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());
    }
    

    Here’s the example of regular expresion that accepts unicode:

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

    Example is given below:

    function validateEmail(email) {
      var re = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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 $result = $("#result");
      var email = $("#email").val();
      $result.text("");
      if (validateEmail(email)) {
        $result.text(email + " is valid :)");
        $result.css("color", "green");
      }      else {
        $result.text(email + " is not valid :(");
        $result.css("color", "red");
      }
       return false;
    }
    $("#validate").bind("click", validate);
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <p>Enter an email address:</p>
      <input id='email'>
      <button type='submit' id='validate'>Validate!</button>
    </form>
    <h2 id='result'></h2>
    
    Answered on December 14, 2018.
    Add Comment

    Here is a simple validation  form:

    Regular expression:

    /\[email protected]\S+\.\S+/
    

    Example JavaScript function:

    function validateEmail(email)
    {
      var re = /\[email protected]\S+\.\S+/;
      return re.test(email);
    }
    
    Answered on December 14, 2018.
    Add Comment

    Try this code:

    To catch the most obvious syntax errors, you can try this:

    ^\[email protected]\S+$
    
    

    It will catches the most obvious errors but user makes and assures form is mostly right, which is all about  JavaScript validation.

    Answered on December 16, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.