Could these WordPress Themes be any more beautiful?
Find out now

Email validation in JavaScript | Step by step tutorial with live demo

Email validation is a very important step when any form capturing email address is submitted on a web page.

Example of an email address: [email protected]

Different ways to do email validation

There are two ways to do email validation:

  1. In web browser itself using JavaScript and
  2. On server-side using programming language like PHP

In this tutorial, we are going to focus on the first way i.e. email validation in JavaScript which is done in the web browser only.

Before getting started with email validation in JavaScript lets have a look at the format of an email address. We need to be very clear about which characters are allowed and which are not in an email address.

Knowing this will help us to write the logic for email validation in JavaScript.

Format of an email address

The format of an email address is [email protected] where local-part can be up to 64 characters long and the domain can be up to 255 characters long.

Characters allowed in local-part

The local-part can have any of the below mentioned ASCII characters :

  1. Uppercase ( A - Z) and lowercase (a - z) letters
  2. Digits (0 - 9)
  3. Printable characters: ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  4. Dot (.), the dot must not be the first and last character of local-part and also it must not come one after another (e.g. [email protected] is not a valid email address as it contains two consecutive dots)

Characters allowed in domain

The domain-name can have any of the below mentioned characters:

  1. Uppercase ( A - Z) and lowercase (a - z) letters
  2. Digits (0 - 9)
  3. Hyphen (-), it should not be the first or last character of the domain
  4. Dots(.)

Now as we know what characters are allowed in an email address so we can write our email validation logic.

Email validation RegExp

To check whether an email address is valid or not we will use JavaScript regular expressions.

To perform email validation in JavaScript we will use below regular expression:

/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(.\w{2,3})+$/

Explanation of the email validation RegExp

RegExp CharactersDescription
/ … /Regular expressions start and end with forward slashes.
^It is known as position anchor. It matches the beginning of the string.
\w+\w is a metacharacter, it matches a character and using “+ after it makes it to match one or more letters, number, or underscore (this is the same as [a-zA-Z0-9_]).
[.-]Big brackets represent “character class“, it will match characters inside them i.e. dot(.) and dash(-).
?? is known as “occurrence indicator“. It matches zero or one occurrence.
** is another “occurrence indicator”. It matches zero or more occurrences.
@It matches single @ character
([.-]?\w+)*Starting and closing brackets represent “character class”, this character class is having * at the end so it will match zero or more occurrences of sub-expression[.-]?\w+
\w+([.-]?\w+)*This sub-expression matches the domain name which is also known as SLD(Second Level Domain). For example in [email protected], gmail is the domain name.
(.\w{2,3})+This sub-expression matches the TLD(Top Level Domain). For example in [email protected], com is the top-level domain.
.\w{2,3}It matches TLD e.g. .com, .org, .pro, etc.
\w{2,3}It matches words that are either 2 or 3 characters long. e.g. com, org, pro, etc.
If you want to match more lengths other than 2 and 3 then pass them as separated by a comma e.g. \w{2,3,4}
++ is an “occurrence indicator“. It matches one or more occurrences.
$It is a position anchor that matches the end of the line.

Now you understand the regular expression which will validate our email so we can get started with the JavaScript program.

We will need some HTML and CSS as well which are written below:

HTML

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email validation in JavaScript</title>
  </head>

  <body class="flex-center">

    <form id="email-form">
      <div id="form-message" class="invalid">Invalid email address</div>
      <input type="text" placeholder="Enter an email address" id="email-input">
      <input type="submit" value="Submit" id="submit-btn">
    </form>

  </body>

</html>

CSS

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  min-height: 200px;
  background-color: #fafaff;
}

#email-form {
  position: relative;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 10px 20px #c5cbee;
}

#form-message {
  position: absolute;
  z-index: 1;
  top: -13px;
  font-family: Helvetica;
  font-size: 12px;
  background-color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}

#form-message.invalid {
  color: #F44336;
}

#form-message.valid {
  color: #8BC34A;
}

#email-input {
  font-size: 18px;
  padding: 12px 20px;
  width: 260px;
  color: #000;
  border: 2px solid #3F51B5;
  border-radius: 4px;
  background-color: #f3f4fc;
  z-index: 1;
  position: relative;
}

#submit-btn {
  display: block;
  width: 100%;
  margin-top: 20px;
  font-size: 14px;
  color: #fff;
  background-color: #3f51b5;
  border: 0;
  padding: 10px 13px;
  border-radius: 3px;
  cursor: pointer;
}

Email validation in JavaScript program

var emailForm = document.getElementById('email-form'),
  emailInput = document.getElementById('email-input'),
  emailAddress = '',
  formMessage = document.getElementById('form-message'),
  emailRegEx = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(.\w{2,3})+$/;

// Below line tells: when form is submitted execute the function written on right side of "="
emailForm.onsubmit = function(event) {

  event.preventDefault(); // As we are not using action attribute on the form so this line will prevent the webpage from reloading when the form is submitted
  
  emailAddress = emailInput.value;

  // Below condition checks that there should be something in "emailAddress" variable and it should not be empty string  
if (emailAddress && emailAddress.trim().length > 0) {

    if (emailAddress.match(emailRegEx)) {
      // Control will reach here if string stored in "emailAddress" variable is a valid email address

      addValidClass();
    } else {
      // Control will reach here if string stored in "emailAddress" variable is an invalid email address

      addInvalidClass();
    }
  } else {
    // Control will reach here if there is no value stored in "emailAddress" variable or the value stored is empty string

    addInvalidClass();
  }
}

function addValidClass() {
  formMessage.textContent = 'Valid email address';
  formMessage.classList.add('valid');
  formMessage.classList.remove('invalid');
}

function addInvalidClass() {
  formMessage.textContent = 'Invalid email address';
  formMessage.classList.add('invalid');
  formMessage.classList.remove('valid');
}

Live demo of email validation in JavaScript

Leave a Reply