Email Validation Regex: The Complete Guide for 2026
Validating an email address with a regular expression is the most-viewed topic on Stack Overflow; the top question alone has over 3.5 million views. Yet most of the popular answers are outdated, overly complex, or wrongly reject real email addresses. This guide gives you patterns that work, explains each component, shows correct implementations in JavaScript, Python, React, and Django, and tells you when to go beyond regex.
<input type="email">, published in the WHATWG HTML Living Standard. The formal grammar for what an address may contain lives in RFC 5322, with routing rules in RFC 5321. That is why no short regex is ever fully "correct": the spec permits quoted local parts and comments almost nobody validates for.Why Email Regex Gets So Many Views
The full specification for a valid email address (RFC 5322) is very complex. A complete regex for it runs over 6,000 characters. No developer wants that, and no production system needs it. When you validate email in a web form, the goal is pragmatic: catch obvious typos before submission, ensure a plausible format, and prevent empty or clearly broken inputs from reaching your backend. The pattern that covers 99%+ of real-world email addresses while remaining readable and maintainable is far simpler.
The Best Practical Email Regex
/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Component breakdown
| Pattern part | What it matches | Why included |
|---|---|---|
^ | Start of string | Prevents matching an email embedded in a longer string |
[a-zA-Z0-9._%+\-]+ | Local part (before @) | All common characters in email local parts. The + handles Gmail-style aliases like user+tag@gmail.com |
@ | The @ symbol | Required in every valid email address |
[a-zA-Z0-9.\-]+ | Domain name | Letters, digits, dots (for subdomains), hyphens |
\. | A literal dot | Escaped because dot is a metacharacter meaning "any character" |
[a-zA-Z]{2,} | Top-level domain | Minimum 2 letters, no upper limit, so it handles .com through .international |
$ | End of string | Prevents partial matching: the entire string must be an email |
JavaScript Implementation
// Basic validation function
function isValidEmail(email) {
if (!email || typeof email !== 'string') return false;
const pattern = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
return pattern.test(email.trim().toLowerCase());
}
// Test cases
console.log(isValidEmail('user@example.com')); // true
console.log(isValidEmail('user.name+tag@sub.example.co.uk')); // true
console.log(isValidEmail('user@example.museum')); // true (long TLD)
console.log(isValidEmail('invalid')); // false
console.log(isValidEmail('@nodomain.com')); // false
console.log(isValidEmail('no@tld')); // false
console.log(isValidEmail('spaces here@example.com')); // false
console.log(isValidEmail('')); // false
// In a form validation handler
document.querySelector('form').addEventListener('submit', (e) => {
const email = document.querySelector('[name="email"]').value;
if (!isValidEmail(email)) {
e.preventDefault();
showError('Please enter a valid email address');
}
});
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Performance note for high-volume use
// Compile the regex once outside the function for performance
// Avoids re-compilation on every call in tight loops
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
function isValidEmail(email) {
return typeof email === 'string' && EMAIL_REGEX.test(email.trim().toLowerCase());
}
// Validate 10,000 emails efficiently
const results = emailList.map(isValidEmail);
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Python Implementation
import re
# Compile once, reuse many times
EMAIL_PATTERN = re.compile(
r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$'
)
def is_valid_email(email: str) -> bool:
if not email or not isinstance(email, str):
return False
return bool(EMAIL_PATTERN.match(email.strip().lower()))
# Test cases
test_cases = [
('user@example.com', True),
('user.name@example.com', True),
('user+tag@example.com', True),
('user@sub.example.co.uk', True),
('invalid', False),
('@nodomain.com', False),
('no@tld', False),
('', False),
]
for email, expected in test_cases:
result = is_valid_email(email)
status = '✓' if result == expected else '✗ UNEXPECTED'
print(f' {status} {email!r}: {result}')
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
HTML5 Native Validation: The Simplest Option
Before adding JavaScript, check whether HTML5 native validation covers your requirements. Adding type="email" to an input element activates browser-native validation that catches missing @, missing domain, and obvious format errors, with zero JavaScript.
<!-- HTML5 email validation — no JavaScript needed -->
<input type="email" name="email" required placeholder="you@example.com">
<!-- With additional pattern constraint -->
<input
type="email"
name="email"
required
pattern="[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}"
title="Enter a valid email address (e.g. you@example.com)"
autocomplete="email"
>
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
The limitation: HTML5 validation runs only in the browser and is easily bypassed with a direct HTTP request or curl. Always validate server-side as well. Browser validation is a UX improvement that gives users immediate feedback, not a security control.
React: Real-Time Validation with Good UX
import { useState, useCallback } from 'react';
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
function EmailField({ onValidChange }) {
const [value, setValue] = useState('');
const [dirty, setDirty] = useState(false); // only show error after user interaction
const isValid = EMAIL_REGEX.test(value.trim());
const showError = dirty && value.length > 0 && !isValid;
const handleChange = useCallback((e) => {
const newVal = e.target.value;
setValue(newVal);
onValidChange(EMAIL_REGEX.test(newVal.trim()));
}, [onValidChange]);
return (
<div style={{ marginBottom: 16 }}>
<label style={{ display: 'block', marginBottom: 6, fontSize: 14 }}>
Email address
</label>
<input
type="email"
value={value}
onChange={handleChange}
onBlur={() => setDirty(true)}
placeholder="you@example.com"
autoComplete="email"
style={{
width: '100%',
padding: '8px 12px',
borderRadius: 6,
border: `1px solid ${showError ? '#f87171' : '#374151'}`,
background: '#111',
color: '#e4e4e7',
fontSize: 15,
}}
aria-invalid={showError}
aria-describedby={showError ? 'email-error' : undefined}
/>
{showError && (
<p id="email-error" style={{ color: '#f87171', fontSize: 13, marginTop: 4 }}>
Please enter a valid email address
</p>
)}
</div>
);
}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Express.js and Node.js Server-Side Validation
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
// Middleware for validating email in request body
function validateEmail(req, res, next) {
const { email } = req.body;
if (!email || typeof email !== 'string') {
return res.status(400).json({ error: 'Email is required' });
}
const normalised = email.trim().toLowerCase();
if (!EMAIL_REGEX.test(normalised)) {
return res.status(400).json({ error: 'Invalid email address format' });
}
req.normalisedEmail = normalised; // pass to next handler
next();
}
// Use in routes
app.post('/register', validateEmail, async (req, res) => {
const email = req.normalisedEmail;
// email is now validated and normalised
await createUser({ email });
res.status(201).json({ message: 'User created' });
});
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Django
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
import re
EMAIL_REGEX = re.compile(
r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$'
)
def clean_email(email: str) -> str:
"""Validate and normalise an email address. Raises ValueError if invalid."""
if not email or not isinstance(email, str):
raise ValueError('Email is required')
email = email.strip().lower()
try:
validate_email(email) # Use Django's battle-tested built-in validator
return email
except ValidationError as e:
raise ValueError(f'Invalid email: {e.message}')
# In a Django form
class RegistrationForm(forms.Form):
email = forms.EmailField(
widget=forms.EmailInput(attrs={
'placeholder': 'you@example.com',
'autocomplete': 'email',
})
) # Django's EmailField uses its own validator automatically
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Validating Deliverability With DNS MX Record Check
Regex validates format, not whether the domain can receive email. An address like real.user@doesnotexist-xyz123.com passes any format regex but bounces immediately when you try to send to it. Where deliverability matters (registration flows, mailing list signups), add an MX record check after format validation.
import re
import dns.resolver # pip install dnspython
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$')
def has_mx_records(domain: str) -> bool:
try:
answers = dns.resolver.resolve(domain, 'MX', lifetime=3.0)
return len(answers) > 0
except Exception:
return False
def validate_email_with_dns(email: str) -> dict:
email = email.strip().lower()
if not EMAIL_REGEX.match(email):
return {'valid': False, 'reason': 'Invalid format'}
domain = email.split('@')[1]
if not has_mx_records(domain):
return {'valid': False, 'reason': 'Domain cannot receive email'}
return {'valid': True, 'email': email}
# Usage
result = validate_email_with_dns('user@gmail.com')
print(result) # {'valid': True, 'email': 'user@gmail.com'}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Performance: DNS lookups add 50–300ms per check. Run them asynchronously or in a background job after form submission, not synchronously in a blocking request handler where the user is waiting for a response.
Test Suite: Run These Before Deploying
// JavaScript test suite
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
const VALID = [
'user@example.com',
'user.name@example.com',
'user+tag@example.com', // Gmail-style alias
'user@sub.example.com', // subdomain
'user@example.co.uk', // multi-segment TLD
'user@example.museum', // long TLD
'123@example.com', // digits in local part
'user_name@example.com', // underscore
'user-name@example.com', // hyphen in local part
'USER@EXAMPLE.COM', // uppercase (case-insensitive in practice)
];
const INVALID = [
'',
'notanemail',
'@nodomain.com', // missing local part
'nodomain@', // missing domain
'no@tld', // TLD too short (1 char)
'double@@example.com', // two @ signs
'spaces in@example.com', // space in local part
'user@', // empty domain
'user@.com', // dot at start of domain
];
let passed = 0, failed = 0;
VALID.forEach(e => {
if (EMAIL_REGEX.test(e)) { passed++; }
else { console.error('Should be VALID but failed:', e); failed++; }
});
INVALID.forEach(e => {
if (!EMAIL_REGEX.test(e)) { passed++; }
else { console.error('Should be INVALID but passed:', e); failed++; }
});
console.log(`${passed} passed, ${failed} failed`);
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Paste any of these test cases into ToolPry's Regex Tester to see match results with live highlighting as you adjust the pattern.
What This Regex Does Not Validate
The practical pattern does not validate: quoted local parts with spaces ("user name"@example.com is RFC 5321-valid but almost never used), IP address domain literals (user@[192.168.1.1]), internationalized email addresses with non-ASCII characters, or whether the specific mailbox exists. For internationalized domain names (IDN), use a dedicated library like idna in Python. For mailbox existence, the only reliable check is sending a verification email and confirming the link is clicked.
Using Email Regex in Node.js API Validation Middleware
For REST APIs built with Express or Fastify, email validation belongs in middleware so it runs consistently across all routes that accept email input. This keeps validation logic in one place and ensures every endpoint normalises the email to lowercase before it reaches business logic or database queries.
// middleware/validateEmail.js
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
module.exports = function validateEmailMiddleware(req, res, next) {
const raw = req.body?.email;
if (!raw || typeof raw !== 'string') {
return res.status(400).json({ error: 'email is required' });
}
const email = raw.trim().toLowerCase();
if (!EMAIL_REGEX.test(email)) {
return res.status(400).json({
error: 'Invalid email address',
field: 'email',
value: email,
});
}
req.body.email = email; // normalised
next();
};
// router.js
const validateEmail = require('./middleware/validateEmail');
router.post('/subscribe', validateEmail, subscribeHandler);
router.post('/login', validateEmail, loginHandler);
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Email Validation in TypeScript with Type Guards
const EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
// Type guard: narrows string to a branded type for compile-time safety
type Email = string & { readonly __brand: 'Email' };
function isEmail(value: string): value is Email {
return EMAIL_REGEX.test(value.trim().toLowerCase());
}
function parseEmail(value: string): Email {
const normalised = value.trim().toLowerCase();
if (!isEmail(normalised)) {
throw new Error(`Invalid email address: ${value}`);
}
return normalised as Email;
}
// Usage
const email = parseEmail('USER@EXAMPLE.COM'); // returns 'user@example.com' as Email type
// TypeScript now knows this variable holds a valid email
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Handling Edge Cases That Break Common Regex Patterns
Even a well-crafted email regex will meet inputs that expose its weaknesses. Knowing these edge cases helps you decide whether your pattern is good enough for your use case or whether you need a library.
The first common edge case is the subaddress or plus alias. Gmail, Fastmail, and many other providers support addresses like user+newsletter@gmail.com. The part after the plus sign is ignored for delivery but is technically part of the local part. Any email regex that excludes the + character from the local part character class will incorrectly reject these addresses, which are widely used for email filtering and tracking.
The second edge case is dots in unexpected positions. RFC 5321 allows multiple consecutive dots in the local part (user..name@example.com) and a dot immediately before the @ sign (user.@example.com). Most real mail servers reject these, but the strict RFC allows them. Unless you are specifically targeting RFC 5321 compliance, treating these as invalid is a sensible choice, since almost no real user has such an address.
The third case is new and long TLDs. ICANN has approved hundreds of new generic TLDs in recent years: .academy, .software, .international, .photography. Any pattern that caps the TLD length, such as [a-zA-Z]{2,6}, incorrectly rejects these valid addresses. The pattern [a-zA-Z]{2,} with no upper bound handles all current and future TLDs correctly.
The fourth edge case is internationalized domain names. Domain names can now use non-ASCII characters through Punycode encoding: münchen.de encodes to xn--mnchen-3ya.de. Standard ASCII-only email regex handles the encoded Punycode form correctly but not the original Unicode representation. If your users include people whose domains use non-Latin scripts, use a library that handles IDN: Python's email-validator does this natively.
When Not to Use Regex for Email Validation
In some scenarios regex validation alone is not enough and can cause user experience problems. The most important is account recovery. If a user mistyped their email during registration and later cannot log in, your validation preventing them from entering the same typo during recovery helps, but blocking a valid, corrected email because your regex has a bug creates a support burden. Err toward permissive validation on recovery flows.
The second scenario is B2B applications where users enter corporate email addresses. Some companies use non-standard local part characters, internal TLDs on private domains, or email routing through gateways that modify addresses. In these cases, after initial format validation, the most reliable approach is to send a confirmation email and require the user to click a link. That proves the address exists and is reachable, which no regex can determine.
Where deliverability matters more than format (mailing lists, transactional notifications, account verification flows), the only reliable validation is sending a confirmation email. Regex catches typos; it cannot catch mistyped-but-valid addresses like user@gamil.com or user@hotmial.com. Libraries that perform typo detection and suggest corrections (did you mean gmail.com?) provide better user experience than regex alone for catching these common mistakes.
Email Regex FAQ
Should I use regex or an email validation library?
For simple browser-side format validation in a web form, a well-tested regex is fine. For backend production validation where security, internationalisation, or deliverability matter, use a dedicated library. In JavaScript, validator.js has an isEmail() function tested against comprehensive edge cases. In Python, email-validator combines format checking and DNS verification in one call. In Django, the built-in EmailValidator handles the common cases. Libraries are updated when standards change — a regex you write today may reject valid addresses as new TLDs are introduced.
Must I store email addresses in lowercase?
Yes. The domain part is case-insensitive, as DNS names are — USER@EXAMPLE.COM and user@example.com reach the same mailbox. The local part is technically case-sensitive per the RFC but virtually all real mail servers treat it as case-insensitive. Always normalise with email.trim().toLowerCase() before storing to prevent duplicate accounts and ensure consistent database lookups.
Why does my email regex reject valid addresses?
The most common causes: TLD length restriction set too tightly — using [a-zA-Z]{2,6} instead of [a-zA-Z]{2,} rejects long TLDs like .international or .academy. The + sign missing from the local part character class — this rejects user+tag@gmail.com, a widely used pattern. A case-sensitive pattern rejecting uppercase addresses — always normalise to lowercase before testing. Missing the hyphen in the character class — the hyphen must be first or last inside [] to be treated as a literal, not a range operator.
How do I validate multiple emails at once?
// JavaScript — validate comma-separated emails
function validateEmailList(input) {
const emails = input.split(',').map(e => e.trim()).filter(Boolean);
const regex = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
const valid = [];
const invalid = [];
for (const email of emails) {
(regex.test(email.toLowerCase()) ? valid : invalid).push(email);
}
return { valid, invalid };
}
const result = validateEmailList('a@b.com, invalid, c@d.org');
// { valid: ['a@b.com', 'c@d.org'], invalid: ['invalid'] }
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Use ToolPry's Regex Tester to paste your pattern and test multiple email addresses simultaneously with live match highlighting before deploying to production.
How can I suggest a corrected email when a user makes a typo?
Use a library that performs domain typo detection. In JavaScript, mailcheck.js compares the entered domain against a list of known providers and suggests corrections for common typos like gamil.com → gmail.com or hotmial.com → hotmail.com. In Python, the email-validator package has similar functionality. Show the suggestion as a non-blocking prompt — "Did you mean user@gmail.com?" — rather than blocking form submission, since the correction might not always be right.
Permissive regex plus a confirmation email
Before you ship any pattern, test it in the ToolPry Regex Tester against the cases that break it: user+tag@sub.example.co.uk, quoted local parts, and the typo'd domains your users submit. The right strategy is almost always a permissive regex for instant feedback plus a real confirmation email, not a stricter pattern that silently rejects valid addresses.