Open In App

JavaScript Program to Validate An Email Address

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to Validate An Email Address in JavaScript. Validating an email address is a common task in web development. It involves ensuring that an email address entered by a user conforms to a valid format.

Approach 1: Regular Expression

This approach involves defining a regular expression pattern that matches valid email formats. We can then use the test() method of the regular expression object to check if an input string matches the pattern.

Syntax:

const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const isValid = emailPattern.test(email);

Javascript




const email = "nikhil@gmail.com";
const emailPattern = 
    /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const isValid = emailPattern.test(email);
console.log(isValid);


Output

true

Approach 2: Using Library Validator

Install the “validator” library in your Node.js project using npm (Node Package Manager). Open the terminal or command prompt and run the following command:

npm install validator

Syntax:

const validator = require("validator");

Example: Below is the implementation of the above approach

Javascript




const validator = require("validator");
const email = "hello@gmail,com";
const isValid = validator.isEmail(email);
console.log(isValid); 


Output:

False

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads