,

Validate Email Using jQuery

Posted by

We will learn how to use jQuery to validate emails in this tutorial. Regular expressions, or regex, will be used in jQuery to validate emails. Form data on the client-side server or web browser is validated using Javascript. Validation on the client side is quicker than validation on the server side. Thus, we will study how to use JavaScript to validate email addresses.

Validating an email address is more difficult than validating other forms. Thus, in order to validate emails, we will develop a regex. We will use regex to check the first portion of the email address, which is the user name after the @ symbol, and the third part, which is the domain name.

So let’s look at how to validate emails using regex, jquery for email address validation, and javascript.

HTML:

<html>
  <head>
    <title>How To Validate Email Using jQuery</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <form>
      <p>Enter an email address:</p>
      <input id='email'>
      <button type='submit' id='validate'>Validate Email</button>
    </form>
    <div id='result'></div>
    <script>
      function validateEmail(email) {
        let res = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        return res.test(email);
      }
      function validate() {
        let result = $("#result");
        let 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").on("click", validate);
    </script>
  </body>
</html>

Output:

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x