Table of contents
1.
Introduction
2.
What is Validation?
3.
Why is Validation Important?
4.
How to Validate Email Using JavaScript
4.1.
Example 1: Using Regular Expressions
4.2.
Example 2: Using HTML5 and JavaScript
5.
Using Library validator.js
5.1.
Steps to Use validator.js
6.
Frequently Asked Questions
6.1.
Why is email validation important?
6.2.
Can I rely only on the HTML5 type="email" for validation?
6.3.
What are the advantages of using validator.js?
7.
Conclusion
Last Updated: Dec 18, 2024
Easy

Email Validation in JavaScript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Email validation is an essential part of any application where users are required to provide their email addresses. It ensures that the provided email address follows a specific structure and meets predefined rules, improving the quality of data collected. 

Email Validation in JavaScript

In this article, we will discuss what validation is, how to validate email addresses using JavaScript, and how to simplify the process using a library like validator.js.

What is Validation?

Validation is the process of ensuring that user inputs meet the expected format and constraints before processing them. For instance, in email validation, the goal is to verify that the input resembles a valid email address, such as username@example.com.

Why is Validation Important?

  • Data Integrity: Ensures the collected data is accurate and usable.
     
  • Security: Prevents malicious inputs that can harm the application.
     
  • User Experience: Guides users to provide correct information.
     

An invalid email address can lead to communication errors, failed registrations, or other functional issues. Therefore, email validation is a crucial step in form submissions.

How to Validate Email Using JavaScript

JavaScript provides straightforward ways to validate email addresses using regular expressions (RegEx). Below, we will explore how to perform email validation step-by-step.

Example 1: Using Regular Expressions

function validateEmail(email) {
  const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,7}$/;
  return emailRegex.test(email);
}
// Example Usage
const email1 = "user@example.com";
const email2 = "invalid-email";
console.log(validateEmail(email1)); 
console.log(validateEmail(email2));
You can also try this code with Online Javascript Compiler
Run Code


Output

true
false

 

Explanation

  • Pattern:
    • ^[\w.-]+ ensures the username consists of alphanumeric characters, dots (.), or hyphens (-).
       
    • @[\w.-]+ ensures there is an @ symbol followed by a valid domain name.
       
    • \.[a-zA-Z]{2,7}$ ensures a valid domain extension with 2 to 7 characters, like .com, .org, etc.

Example 2: Using HTML5 and JavaScript

HTML5 provides a built-in way to validate email input using the type="email" attribute. However, additional JavaScript validation ensures stricter control.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation</title>
</head>
<body>
  <form id="emailForm">
    <label for="email">Enter your email:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">Submit</button>
    <p id="message"></p>
  </form>


  <script>
    document.getElementById("emailForm").addEventListener("submit", function(event) {
      event.preventDefault();
      const emailInput = document.getElementById("email").value;
      const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,7}$/;


      if (emailRegex.test(emailInput)) {
        document.getElementById("message").textContent = "Valid email address!";
      } else {
        document.getElementById("message").textContent = "Invalid email address.";
      }
    });
  </script>
</body>
</html>


Output

  • Entering user@example.com displays: "Valid email address!"
     
  • Entering userexample displays: "Invalid email address."
Output

Advantages

  • The HTML5 type="email" provides basic validation, while JavaScript adds robust custom checks.

Using Library validator.js

validator.js is a popular JavaScript library that provides a wide range of validation functions, including email validation. It simplifies the process of validating email addresses by offering a pre-built method specifically designed for this purpose.

Steps to Use validator.js

  • Install the library via npm or CDN.
npm install validator

 

  • Import the library and use the isEmail function.
     

Once installed, you can import the library into your JavaScript file using the `require` statement:
 

const validator = require('validator');

 

With the library imported, you can now use the `isEmail` method provided by validator.js to validate email addresses. 

For example:

const email = 'example@example.com';


if (validator.isEmail(email)) {
  console.log('Valid email address');
} else {
  console.log('Invalid email address');
}


This code snippet demonstrates an email address stored in the email variable, which is then passed to the validator.isEmail() method. This method evaluates whether the email address meets the library's validation criteria. If valid, it returns true, and "Valid email address" is logged to the console. Otherwise, it returns false, and "Invalid email address" is displayed.

Validator.js also offers additional options to customize email validation. For instance, you can choose to permit IP addresses as valid domains or allow specific special characters. Detailed information about these customization options is available in the validator.js documentation.

Example

// Import the library
const validator = require('validator');

function validateEmailUsingLibrary(email) {
  return validator.isEmail(email);
}

// Example Usage
const email1 = "user@example.com";
const email2 = "invalid-email";

console.log(validateEmailUsingLibrary(email1)); 
console.log(validateEmailUsingLibrary(email2));
You can also try this code with Online Javascript Compiler
Run Code

 

Output

true
false


Advantages of Using validator.js

  • Ease of Use: Prebuilt functions like isEmail save development time.
     
  • Reliable: Regularly updated and tested for various edge cases.
     

Example with Frontend

You can also use validator.js in a browser-based application.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation with validator.js</title>
  <script src="https://cdn.jsdelivr.net/npm/validator@13.9.0/validator.min.js"></script>
</head>
<body>
  <form id="emailForm">
    <label for="email">Enter your email:</label>
    <input type="text" id="email" name="email" required>
    <button type="submit">Submit</button>
    <p id="message"></p>
  </form>

  <script>
    document.getElementById("emailForm").addEventListener("submit", function(event) {
      event.preventDefault();
      const emailInput = document.getElementById("email").value;
      if (validator.isEmail(emailInput)) {
        document.getElementById("message").textContent = "Valid email address!";
      } else {
        document.getElementById("message").textContent = "Invalid email address.";
      }
    });
  </script>
</body>
</html>


Output

Output

Frequently Asked Questions

Why is email validation important?

Email validation ensures that email addresses are correctly formatted, enhancing data accuracy, reliable communication, and better application security.

Can I rely only on the HTML5 type="email" for validation?

HTML5 provides basic email validation, but combining it with JavaScript allows for stricter checks and the implementation of customized validation rules.

What are the advantages of using validator.js?

Validator.js streamlines email validation with built-in functions like isEmail, making the code cleaner, easier to maintain, and more dependable.

Conclusion

Email validation plays a crucial role in ensuring that only properly formatted email addresses are accepted in applications. JavaScript provides flexible solutions for email validation, ranging from using regular expressions to integrating libraries like validator.js. These practices help developers enhance data quality and improve the overall user experience in their applications.

You can also check out our other blogs on Code360.

Live masterclass