How to validate an email address in JavaScript

JavaScript is a lightweight programming language and is most known as a scripting language for web pages. It is used to create web pages and handle various HTML form validation.

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

You can use a regular expression to validate an email address in JavaScript.

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

If you are in a hurry
A regular expression defining your expectation, matching the format, can be used to validate an email address.
Code

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)!= null?" Valid email address":" In Valid email address";
};

console.log("1. "+isValidEmail("[email protected]"));
console.log("2. "+isValidEmail("user"));

Output

"1. Valid email address"
"2. In Valid email address"

The above pattern validates the email address, and the validation result is printed.

There are a couple of other ways to validate an email address in JavaScript, 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.
    The structure of almost all email addresses will be like [email protected]

Some valid and invalid email address comparisons are listed below,

Valid Email addressInvalid Email address
[email protected]user.techmam.com
[email protected][email protected]@jsowl.com
[email protected]this is”invalid”@gmail.com

Using Regular expression

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

In JavaScript, regular expressions are also objects, and you can use regular expressions to validate an email address.

You can achieve creating regular expression patterns in two ways,

  • Using literal
    Literal consists of a pattern enclosed between slashes, as shown below, const regexLiteral = /[0-9]{1}/ The above pattern is used to accept only one character, and that is of number type.
  • Using RegExp Object
    You have to call the constructor function of the RegEx object as shown below,
    const regexPattern = new RegExp('[0-9]{1}');
    The above pattern is used to accept only one character, and that is of number type.

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);
      return email.match(regex)!= null?" Valid email address":" In Valid email address";
    };

    const validateUsingRegex = () => {
      const regexResult = document.getElementById("regexResult");
      const email = document.getElementById("email").value;
      if (isValidEmail(email)) {
        document.getElementById("regexResult").textContent = email + ' is valid';
        document.getElementById("regexResult").style.backgroundColor = "green";
      } else {
        document.getElementById("regexResult").textContent = email + ' is not valid';
        document.getElementById("regexResult").style.backgroundColor = "red";
      }
      return false;
    }

//html file

    <!DOCTYPE html>
    <html>
      <head>
        <title>TechMam: How to validate an email address in JavaScript</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>
          <div>
            <label>Click to validate: </label>
            <input type="submit">
          </div>
        </form>
      </body>
    </html>

//css file

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

You can use the above complete set of codes to validate an email address inside an HTML form in JavaScript.
Note: Prefix and domain validation expectation is subject to change based on the business requirement.

Validate multiple email addresses

Sometimes you may not require complex email validation. You may need the prefix value validated, and the domain section remains a constant value.
In those scenarios, you can have a simple RegEx to validate the email like below,

Code

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

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

Output

    true
    false

In the above example, As the first email address([email protected]) matches with the Regex pattern, it returns True
In the second email([email protected]) scenario, even though it looks logically correct, it returns false as it does not match the pattern.

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

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

Output

    false
    true
    false

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

Using HTML5 input and JavaScript

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 a 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
//html

    <!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 email = document.getElementById("email-id").value;
    document.getElementById("html5result").textContent = email + ' is valid';
    document.getElementById("html5result").style.backgroundColor = "green";
}

Live Demo

Summary

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

You May Also Like

Leave a Comment