validate
javascript
address
email

How can I validate an email address in JavaScript?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Validating an email address in JavaScript can be done using a regular expression (regex). Below are different methods you can use to validate an email address:

1. Basic Email Validation with Regular Expression

A simple and commonly used regex pattern for basic email validation is:

javascript
1function validateEmail(email) {
2    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
3    return re.test(email);
4}
5
6// Example usage
7console.log(validateEmail("[email protected]")); // true
8console.log(validateEmail("invalid-email"));    // false
  • ^[^\s@]+@[^\s@]+\.[^\s@]+$: This pattern matches a string that:
    • ^[^\s@]+: Starts with one or more characters that are not whitespace or @.
    • @[^\s@]+\.: Contains an @ symbol followed by one or more characters that are not whitespace or @, followed by a ..
    • [^\s@]+$: Ends with one or more characters that are not whitespace or @.

This regex is sufficient for many cases, but it may not cover every edge case of the email format according to the official specification (RFC 5322).

2. Advanced Email Validation with a More Comprehensive Regex

For a more robust validation that covers a wider range of valid email addresses, you can use a more complex regex pattern:

javascript
1function validateEmail(email) {
2    const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
3    return re.test(email);
4}
5
6// Example usage
7console.log(validateEmail("[email protected]")); // true
8console.log(validateEmail("[email protected]")); // true
9console.log(validateEmail("[email protected]"));   // true
10console.log(validateEmail("invalid-email"));    // false
11console.log(validateEmail("[email protected]"));     // false
  • ^[a-zA-Z0-9._%+-]+: Matches the local part (before the @) consisting of alphanumeric characters and special characters like ., _, %, +, -.
  • @[a-zA-Z0-9.-]+: Matches the domain part (after the @), which can include alphanumeric characters, dots, and hyphens.
  • \.[a-zA-Z]{2,}$: Ensures that the domain ends with a dot followed by at least two alphabetical characters (like .com, .net).

3. Using HTML5 Built-in Email Validation

If you're working with forms in HTML, you can also use the built-in email validation provided by the type="email" attribute:

html
1<form>
2    <input type="email" id="email" required>
3    <button type="submit">Submit</button>
4</form>

This approach uses the browser's built-in validation, which can be supplemented with JavaScript for additional checks:

javascript
1const emailInput = document.getElementById("email");
2
3emailInput.addEventListener("input", function() {
4    if (emailInput.validity.typeMismatch) {
5        emailInput.setCustomValidity("Please enter a valid email address!");
6    } else {
7        emailInput.setCustomValidity("");
8    }
9});

4. Using External Libraries

For very comprehensive validation, you can also use external libraries like validator.js which provides a robust email validation function:

javascript
1// First, include validator.js in your project
2// For example, using npm: npm install validator
3
4const validator = require('validator');
5
6console.log(validator.isEmail('[email protected]')); // true
7console.log(validator.isEmail('invalid-email'));    // false

Summary

  • Basic Validation: Use a simple regex for straightforward email validation.
  • Advanced Validation: Use a more complex regex for a wider range of valid email formats.
  • HTML5 Validation: Leverage the browser's built-in email validation in forms.
  • External Libraries: Use a library like validator.js for comprehensive validation.

Each method has its use case depending on the complexity and requirements of your application.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.