Back

How to Validate Email Addresses with Regex in JavaScript

The Problem

You need to validate that a user's input is a properly formatted email address before submitting a form or processing data.

The Solution (TL;DR)

Here's a reliable regex pattern for email validation in JavaScript:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; function isValidEmail(email) { return emailRegex.test(email); } // Usage console.log(isValidEmail("[email protected]")); // true console.log(isValidEmail("invalid-email")); // false console.log(isValidEmail("[email protected]")); // true

How It Works

Let's break down the regex pattern:

Pattern PartMeaning
^Start of string
[a-zA-Z0-9._%+-]+One or more valid characters for the local part (before @)
@Literal @ symbol
[a-zA-Z0-9.-]+One or more valid domain characters
\.Literal dot
[a-zA-Z]{2,}TLD with at least 2 letters
$End of string

More Strict RFC 5322 Compliant Version

For edge cases and stricter validation:

const strictEmailRegex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;

⚠️ Note: This complex regex covers more edge cases but is harder to maintain. For most web applications, the simple version is sufficient.

Real-World Usage Example

// Form validation example document.getElementById('email-form').addEventListener('submit', (e) => { const email = document.getElementById('email').value; if (!isValidEmail(email)) { e.preventDefault(); alert('Please enter a valid email address'); return; } // Proceed with form submission });

The "Lazy" Alternative

Don't want to write and test regex? Use the free Regex Tester on Pockit to quickly validate and debug your regex patterns with real-time matching visualization.

JavaScriptTutorialSnippetsRegexValidation

Explore Related Tools

Try these free developer tools from Pockit