Open In App

Validate Email in JavaScript

Last Updated : 02 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various methods to validate email in JavaScript

1. Simple Validation with Regular Expression

JavaScript
function valid(email) {
    const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return pattern.test(email);
}
const email = "[email protected]";
console.log(valid(email) ? "Valid email address" : "Invalid email address");

Output
Valid email address

In this example

  • The valid function checks whether a given email address matches the standard email format using a regular expression.
  • The pattern ^[^\s@]+@[^\s@]+\.[^\s@]+$ ensures the email has a valid structure: it starts with characters other than spaces or "@" ([^\s@]+), followed by an "@" symbol, a domain name, and a valid top-level domain.

2. Using Library validator.js

For robust email validation, we can use npm libraries like validator.js. before using it, first install it using npm.

npm install validator
JavaScript
const valid = require("validator");
const emailToValidate = "[email protected]";
console.log(valid.isEmail(emailToValidate)
    ? "Valid email address"
    : "Invalid email address");

Output

Valid email address

In this example

  • The validator library's isEmail function is used to check whether the given email address is valid.
  • The isEmail method evaluates "[email protected]" and returns true if it matches the standard email format.

3. Validate Multiple Emails

JavaScript
const emails = [
    "[email protected]",
    "invalid-email.com",
    "[email protected]"
];
emails.forEach(email => {
    console.log(`${email} is ${validator.isEmail(email) ? 'valid' : 'invalid'}.`);
});

In this example

  • An array of email addresses is iterated using forEach, where each email is checked using the validator.isEmail function.
  • The function determines whether each email matches the standard format and logs the result in the format: "email is valid" or "email is invalid".

4. Built-in HTML5 Validation

JavaScript
function valid(email) {
    const input = document.createElement('input');
    input.type = 'email';
    input.value = email;
    return input.checkValidity();
}
console.log(valid("[email protected]") ? "Valid email" : "Invalid email");


In this example

  • The valid function checks if the provided email is valid using an <input> element with type "email".
  • The console.log statement logs "Valid email" or "Invalid email" based on the result.

Next Article

Similar Reads