Email validation regex in JavaScript
Advanced · 4 min read
Almost every sign-up form has an email field, and almost every one checks it with a regular expression before letting you continue. The check catches obvious slips, like a missing @ or a space in the middle, before the form is sent.
In this tutorial you will build an email pattern piece by piece, instead of copying a long line you can't read. The exercise has one tricky rule: the part before the @ may contain dots, but never as the first character, never as the last, and never two in a row. You need to know /.../.test(), ^, $ and character classes like [A-Z]. The rest is explained as we go.
The two halves of an address
An address like ada.obi@example.com has two halves:
- the local part, before the
@:ada.obi - the domain, after it:
example.com
We will write a pattern for each half, then join them with an @.
Building a pattern from strings
A long pattern is easier to read when you build it from named pieces. new RegExp(text) turns a string into a regular expression:
const DIGITS = '\\d+';
const pattern = new RegExp('^' + DIGITS + '$');
console.log(pattern); // /^\d+$/
console.log(pattern.test('2025')); // true
Inside a normal string, a backslash has to be written twice. The string '\\d+' holds the three characters \d+, which is what the pattern needs.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
3 A pattern for email addresses
hardMatch email addresses. The source is specific: the local part allows letters, digits and ! # $ % & ' * + - / = ? ^ _ ` { | } ~, and a dot that is neither first nor last and never doubled.
Stuck? Three hints, smallest first
- 1. Build the local part as: one allowed character, then optionally more groups of "dot then characters".
- 2. That structure makes a leading dot, a trailing dot and a double dot impossible without any lookahead.
- 3. The only real check that an address works is sending a message to it.
Step 1: the allowed characters
The exercise lists the characters allowed in the local part: letters, digits and a set of symbols. Put them in one character class, with the dash last so it means a real dash and not a range. This is one atom, one allowed character:
const ATOM = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";
const local = new RegExp('^' + ATOM + '+$');
console.log(local.test('ada')); // true
console.log(local.test("o'brien")); // true
console.log(local.test('ada.obi')); // false: no dot yet
The dot is missing on purpose. It has special rules, so it gets its own step.
Step 2: the wrong way to add the dot
The obvious move is to put the dot inside the class too:
const loose = /^[A-Za-z0-9.]+$/;
console.log(loose.test('ada.obi')); // true
console.log(loose.test('.ada')); // true, but a leading dot is not allowed
console.log(loose.test('ada..obi')); // true, but a double dot is not allowed
Now a dot can go anywhere, including the three places the rule forbids.
Step 3: let the shape forbid bad dots
Here is the trick. Describe the local part as "one or more atoms, then any number of groups of a dot followed by one or more atoms":
atom+ ( . atom+ )*
ada .obi -> ada.obi
(?: ... ) is a group that just bundles things together, and * after it means "zero or more times". A dot can now only appear between atoms, so a leading dot, a trailing dot and a double dot simply can't match:
const ATOM = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";
const LOCAL = ATOM + '+(?:\\.' + ATOM + '+)*';
const local = new RegExp('^' + LOCAL + '$');
console.log(local.test('ada.obi')); // true
console.log(local.test('.ada')); // false
console.log(local.test('ada.')); // false
console.log(local.test('ada..obi')); // false
\. means a real dot. Without the backslash, a dot in a pattern means "any character".
Step 4: the domain
A domain is made of labels separated by dots: example and com. A label starts and ends with a letter or digit and can have dashes inside. The answer allows up to 63 characters per label, and (?:\.label)+ with a + demands at least one dot:
const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const DOMAIN = LABEL + '(?:\\.' + LABEL + ')+';
const domain = new RegExp('^' + DOMAIN + '$');
console.log(domain.test('example.com')); // true
console.log(domain.test('example.co.uk')); // true
console.log(domain.test('example')); // false: no dot
Step 5: join the halves
Put @ between the halves, anchor both ends, and add a length limit (addresses can be at most 254 characters):
const ATOM = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";
const LOCAL = ATOM + '+(?:\\.' + ATOM + '+)*';
const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const DOMAIN = LABEL + '(?:\\.' + LABEL + ')+';
const EMAIL = new RegExp('^' + LOCAL + '@' + DOMAIN + '$');
const matchesEmail = (value) => typeof value === 'string' && value.length <= 254 && EMAIL.test(value);
console.log(matchesEmail('ada+bus@example.co.uk')); // true
console.log(matchesEmail('ada@@example.com')); // false
console.log(matchesEmail('ada@gmial.com')); // true, even with the typo
The last line matters. A pattern can't know whether an address exists or is spelled the way you meant.
The full solution
The panel builds the same pattern with template strings and runs it over a list of good and bad addresses. Press Run. The last two checks show nonsense and typos still passing, which is why the only real test is sending an email.
// The character set the question allows, minus the dot.
const ATOM = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";
/* Local part = atom+ then zero or more of (dot atom+). This shape makes
".a", "a." and "a..b" unmatchable, so no lookahead is needed. */
const LOCAL = `${ATOM}+(?:\\.${ATOM}+)*`;
const DOMAIN = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+';
const EMAIL = new RegExp(`^${LOCAL}@${DOMAIN}$`);
const matchesEmail = (value) => typeof value === 'string' && value.length <= 254 && EMAIL.test(value);
const good = [
'ada@example.com',
'ada.obi@example.com',
"o'brien@example.com",
'a!#$%&*+-/=?^_`{|}~b@example.com',
'ada+bus@example.co.uk',
'a@b.co',
];
const bad = [
'.ada@example.com', // dot first
'ada.@example.com', // dot last
'ada..obi@example.com', // doubled dot
'ada@example', // no dot in the domain
'ada@@example.com',
'ada example@x.com', // space
'@example.com',
'ada@',
'',
];
for (const e of good) console.log('should match ', e.padEnd(34), matchesEmail(e));
for (const e of bad) console.log('should not ', JSON.stringify(e).padEnd(34), matchesEmail(e));
Output
18 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 18 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain address matches', matchesEmail('ada@example.com'), true);
test('a dot inside the local part is allowed', matchesEmail('ada.obi@example.com'), true);
test('an apostrophe is allowed, as the question allows', matchesEmail("o'brien@example.com"), true);
test('every listed special character together', matchesEmail('a!#$%&*+-/=?^_`{|}~b@example.com'), true);
test('a plus sign is allowed', matchesEmail('ada+bus@example.co.uk'), true);
test('a leading dot is refused', matchesEmail('.ada@example.com'), false);
test('a trailing dot is refused', matchesEmail('ada.@example.com'), false);
test('a doubled dot is refused', matchesEmail('ada..obi@example.com'), false);
test('a domain with no dot is refused', matchesEmail('ada@example'), false);
test('two at-signs are refused', matchesEmail('ada@@example.com'), false);
test('a space is refused', matchesEmail('ada example@x.com'), false);
test('an empty local part is refused', matchesEmail('@example.com'), false);
test('an empty domain is refused', matchesEmail('ada@'), false);
test('an empty string is refused', matchesEmail(''), false);
test('every good example matches', good.every(matchesEmail), true);
test('and no bad one does', bad.some(matchesEmail), false);
test('but a nonsense address that LOOKS right still passes', matchesEmail('nobody@nowhere.example'), true);
test('and so does a typo', matchesEmail('ada@gmial.com'), true);
The structure atom+ (dot atom+)* is the idea worth keeping. Rather than matching anything and then using lookaheads to forbid a leading dot, a trailing dot and a doubled dot, the shape makes all three impossible. Building the pattern from named pieces in template strings also makes it readable — a single 200-character regex literal is unmaintainable, and this one is long even so.
Now the honest part, which the last two assertions make concrete: nobody@nowhere.example and ada@gmial.com both pass. A pattern checks shape. It cannot know whether an address exists, and the only way to find out is to send a message and see. So use a loose pattern to catch obvious slips, always let the user correct it, and never block a submission because your regex disagrees with an address someone tells you is theirs. The full RFC 5322 grammar permits quoted strings, comments and nested parentheses; matching it exactly is possible and pointless.
Common mistakes
- Putting the dot in the character class. That allows
.ada,ada.andada..obi. Use theatom+(\.atom+)*shape instead. - Writing
.instead of\.. An unescaped dot matches any character, soadaXexamplewould count as having a dot. - Blocking people because of the pattern. It catches slips, not fake addresses. Let users correct the field, and confirm the address by sending a message.
Try it yourself
- Add
'.ada@example.com'and'ada.@example.com'to a list and checkmatchesEmailrefuses both. - Write
domainOf(email)that returns the part after the@. (Hint:split('@').) - Make the check case-insensitive by adding the
iflag, then shorten[A-Za-z]to[a-z].