Search
Close this search box.
Search
Close this search box.

Email Validation Using Javascript: A Step-by-Step Tutorial

email validation

Table of Contents

Because it guarantees that the data your application receives is valid and in the desired format, email validation/verification is an essential component of web development. JavaScript’s regular expressions (regex) capability aids with user email verification.

Any website should have email verification since it keeps the site safe by enabling users to use email only who are legitimate and verified.

An email is a string, or a subset of ASCII letters, that has the @ symbol separating it into two parts. The email’s domain name appears in the second section, while user information is contained in the first. The domain name may be up to 253 characters, while the personal information part may contain up to 64 characters.

The Anatomy of an Email Address

Let’s start by going over the basics of an email address before moving on to regular expressions. Generally, an email address consists of two parts:

  1. Local Part: The portion of the email address that appears before the “@” symbol is called the local component. It can contain figures, letters, and special characters like hyphen (-), underscore (_), and period (.).
  2. Domain part: The portion of an email address that defines the domain of the email server and appears after the “@” sign. It can contain hyphens (-), letters, numbers, and periods (.). Additionally, subdomains divided by periods could be present.

Here are a few instances of legitimate email addresses:

1. johnstark@gmail.com
2.Amit_Shah@gmail.com
3. Amit99@gmail.com

Examples of Invalid email addresses:

1.cosw.gmail.com
2.code@gmail.comb
3.you@.net

Using regular expressions for verifying emails

JavaScript has regular expressions integrated, which makes email address validation quite simple. To begin, let’s use a basic regular expression:

				
					const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
				
			

Let’s examine this regular expression in more detail:

  • The anchors ‘^’ and ‘$’ guarantee that the regex matches the full text, beginning to end.
  • [a-zA-Z0-9._-]+’ corresponds to one or more characters, which may be underscores, hyphens, periods, letters, or digits. This is the email’s local content.
  • The @ “@” sign corresponds exactly.
  • [a-zA-Z0-9.-]+ corresponds to one or more characters, which may be hyphens, periods, letters, or numerals. This is the section related to the domain.
  • The top-level domain (TLD) is denoted by the “.” period. 
  • “[a-zA-Z]{2,4}” corresponds to the TLD, which is made up of two to four alphabetical characters.

The following regular expression can be used to validate email addresses when creating JavaScript:

HTML

				
					<div>
  <form action="#" id="form">
    <div class="input-box">
      <input type="text" name="" id="email" placeholder="Enter Email Address" onkeydown="validation()">
      <span id="text"></span>
    </div>
  </form>
</div>
				
			

HTML Output

CSS Styling

				
					* {
  margin: 0;
  padding: 0;
  font-family: 'Poppins', sans-serif;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #373737;
}

#form {
  position: relative;
}

#form #email {
  width: 300px;
  background: #292929;
  outline: none;
  border: none;
  padding: 10px;
  border-radius: 6px;
  color: #fff;
  font-style: 18px;
}

#form .input-box {
  position: relative;
}

#text {
  display: block;
  color: #000;
  font-weight: 300;
  font-style: italic;
  padding: 5px;
}

#form.invalid .input-box::before {
  content: '';
  position: absolute;
  right: 12px;
  top: 9px;
  width: 24px;
  height: 24px;
  background: url(https://fadzrinmadu.github.io/hosted-assets/email-validation-check-using-javascript/invalid.png);
  -webkit-background-size: cover;
  background-size: cover;
}

#form.valid .input-box::before {
  content: '';
  position: absolute;
  right: 12px;
  top: 9px;
  width: 24px;
  height: 24px;
  background: url(https://fadzrinmadu.github.io/hosted-assets/email-validation-check-using-javascript/valid.png);
  -webkit-background-size: cover;
  background-size: cover;
}
				
			

CSS Output

CSS Output

JavaScript Code

				
					function validation() {
  let form = document.getElementById('form')
  let email = document.getElementById('email').value
  let text = document.getElementById('text')
  let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/

  if (email.match(pattern)) {
    form.classList.add('valid')
    form.classList.remove('invalid')
    text.innerHTML = "Your Email Address in valid"
    text.style.color = '#00ff00'
  } else {
    form.classList.remove('valid')
    form.classList.add('invalid')
    text.innerHTML = "Please Enter Valid Email Address"
    text.style.color = '#ff0000'
  }

  if (email == '') {
    form.classList.remove('valid')
    form.classList.remove('invalid')
    text.innerHTML = ""
    text.style.color = '#00ff00'
  }
}
				
			

The validation() JavaScript function verifies if the email entered in a form corresponds to the original email pattern. A green line around the email box indicates a validated email, providing the format of the email follows the given pattern. Additionally, an incorrect email address will be displayed as a red line outside the email box if the email ID is not formatted correctly.

The email input clears all styles and messages if it is empty. Users can get immediate feedback on the legitimacy of their emails with this tool.

Final Output

See the Pen Email Validation Check Using Javascript by Muhammad Fadzrin Madu (@fadzrinmadu) on CodePen.

Code by: Muhammad Fadzrin Mad

Project Link – Codepen

Written by: cssiseasy

Email Validation Flow Chart

Flow Chart

Conclusion

Regular expressions in JavaScript are useful tools for email verification. You may improve the quality of data input in your web applications by learning how email addresses are structured and using regular expressions correctly. However, combine email verification with server-side checks to guarantee a dependable and secure solution. This guarantees that email addresses are correctly formed and are both valid and distributable.

If you find this blog useful, be sure to follow the Instagram page and do a Google search for “cssiseasy” to find frontend projects with source code.

Facebook
Twitter
LinkedIn
Telegram
Email
WhatsApp

1 thought on “Email Validation Using Javascript: A Step-by-Step Tutorial”

  1. Pingback: Creating Math Game Using HTML, CSS & JavaScript - cssiseasy

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top