How to validate an email address in jQuery

jQuery is a small, fast, and feature-rich JavaScript library. It is used to do HTML document traversal and manipulation, event handling, Ajax and also to handle various HTML form validation.

The email option is the most common feature in HTML form to get the user’s email address as an input. An email address is a textual representation which identifies an email box to which messages are delivered.

You can use the jQuery validation plugin to validate an email address in jQuery.

Validating email addresses on the client side using jQuery will help faster data processing than on the server.

If you are in a hurry
JQuery validation plugin provides functionality to validate an email address. It also offers additional functionality to custom the pattern to be validated.
Code

    <form id="myform" onsubmit="event.preventDefault();validateUsingPlugin();">
      <div>
        <label for="field">Enter your email : </label>
        <input class="left" id="field" name="field">

      </div>
      <div>
       <label for="field">Click to validate </label>
        <input type="submit" value="Validate!">
      </div>
    </form>

    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
    <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
        debug: true,
        success: "valid"
      });
      $("#myform").validate({
        rules: {
          field: {
            required: true,
            email: true
          }
        }
      });

    </script>

Here the jQuery validator plugin is linked to the input element, and now, on every form submitted, the validator will validate the input element.
It only allows for successful validation; else, it will notify the user to add a valid email address.
There are a couple of other ways to validate an email address in jQuery and let us see those in detail.

General Valid Email standard

A valid email address should consist of an email prefix and an email domain separated by a @ symbol, both with acceptable formats.

  • The prefix should appear left to @ symbol.
  • The domain should appear right to @ symbol.
    To validate an email address, you have to check for the expected prefix followed by @ and whether a expected domain is present or not.
  • The prefix can be of any ASCII character’s
    • Alphabets (A-Z and a-z)
    • Numbers (0-9)
    • Special Characters (@#$%^&*()…), but it should not appear at the start
  • Thedomain name should match the domain name standard.
    This will be the structure of almost all email addresses, [email protected]

Some valid and invalid email address comparisons are listed below,

Valid EmailInvalid Email
[email protected]jQuery.techmam.com
[email protected][email protected]@jsowl.com
[email protected]iminvalid”@gmail.com

Using JQuery Validate Plugin

JQuery validation plugin helps make client-side form validation easy with plenty of customizable options.
This includes [email validation]() with many custom options like adding a regex pattern, making mandatory field checks with options to specify custom error messages, etc.
Code
//html

    <!DOCTYPE html>
    <html>
        <head>
            <title>TechMam: How to validate an email address</title>
            <link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
        </head>
        <body>
            <form id="myform">
                <div>
                    <label for="field">Enter your email : </label>
                    <input class="left" id="field" name="field">
                </div>
                <div>
                    <label for="field">Click to validate </label>
                    <input type="submit" value="Validate!">
                </div>
            </form>

            <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
            <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
            <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

            <script>
                // avoid form submit, this is just for demo
                jQuery.validator.setDefaults({
                    debug: true,
                    success: "valid"
                });
                $("#myform").validate({
                    rules: {
                        field: {
                            required: true,
                            email: true
                        }
                    }
                });
            </script>
        </body>
    </html>

The above code will help to validate an email address by typing the value in the text input.
If you want a custom pattern for validating email, add the regex attribute inside the rules.field attribute.
You can also use the jQuery validation plugin to validate different form element validations.

Using Regular expression

Regular expressions are string patterns used to match character combinations in strings and also objects.

You can use regular expressions to validate an email address.

You can achieve creating regular expression patterns in two ways,

  • Using literal
    Literals consist of a pattern enclosed between slashes, as shown below,
    const regexLiteral = /[0-9]{1}/
  • Using RegExp Object
    You have to call the constructor function of the RegEx object as shown below,
    const regexObject = new RegExp('ab+c');
    Code
    //javascript file
    const isValidEmail = (email) => {
        const regex = /^(([^<>()[\]\\.,;:\[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 email.match(regex);
    };

    const validateUsingRegex = () => {
        const $regexResult = $('#regexResult');
        const email = $('#email').val();
        $regexResult.text('');
        if (isValidEmail(email)) {
            $regexResult.text(email + ' is valid');
            $regexResult.css('color', 'green');
        } else {
            $regexResult.text(email + ' is not valid');
            $regexResult.css('color', 'red');
        }
        return false;
    }

    $('#email').on('input', validateUsingRegex);

//html file

    <!DOCTYPE html>
    <html>
      <head>
        <title>TechMam: How to validate an email address in jQuery</title>
        //include script file here
      </head>
      <body>
        <h4>Email address validation using Regular expression</h4>
        <form name="usingRegex" onsubmit="event.preventDefault();validateUsingRegex()">
          <div>
            <label for="email">Enter your email : </label>
            <input type="text" id="email" />
            <span id="regexResult"></span>
          </div>
        </form>
      </body>
    </html>

//css file

    body {
        font-size: 16px;
    }
    div {
        padding: 5px;
    }
    input[type=email],
    input[type=text]{
        width: 200px;
        font-size: 12pt;
    }

The above complete code can validate an email address inside an HTML form in jQuery.
Note: Prefix and domain validation expectation is subject to change based on the business requirement.

Using HTML5 input and jQuery

HTML input type=”email” allows you to enter and edit the email address and also to add multiple email addresses with commas separated when you have multiple attribute is added to the input element.

This accepts only email addresses that are considered valid; you can also add a custom pattern for validating the email address.
Code

    <!DOCTYPE html>
    <html>
        <head>
            <title>TechMam: How to validate an email address</title>
        </  head>
        <body>
            <form name="usingHTML5" onsubmit="event.preventDefault();validateUsingHTML5()">
                <div>
                    <label for="email">Enter your email:</label>
                    <input type="email" id="email-id" pattern="[email protected]\.com" name="email">
                    <span id="html5result"></span>
                </div>
                <div>
                    <label>Click to validate: </label>
                    <input type="submit">
                </div>
            </form>
        </body>
    </html>

//javascript

    const validateUsingHTML5 = () => {
        const $html5result = $('#html5result');
        const email = $('#email-id').val();
        $html5result.text(email + ' is valid');
        $html5result.css('color', 'green');
    }

Validate multiple email addresses

There are times you may not require complex email validation. You may need the prefix value to be validated and make the domain section hold a constant value.
In that scenario, you can have a simple Regular expression object to validate the email like below,

Code

    const  isValidEmailAddress = (email) => {
        let  regex = new  RegExp('[a-z0-9][email protected]');
        console.log(regex.test(email));
    }

    isValidEmailAddress ("[email protected]");
    isValidEmailAddress ("[email protected]");

Output

    true
    false

You can also use Regex to validate email addresses in a list in jQuery,
Code

    let  emailList = ["[email protected]","[email protected]", "invalidemail"];
    const  isValidEmail = (emailList) => {
        let  regex = new  RegExp('[a-z0-9][email protected]');
        emailList .forEach((email) => {
            console.log(regex.test(email))
        });
    }
    isValidEmail(emailList);

Output

    true
    false
    false

You have used multiple emails in a list and validated them all at once.

Live Demo

Summary

You have learned how to validate an email address in jQuery.
You have also learnt different ways to use a regular expression to validate an email address.

You May Also Like

Leave a Comment