Emmanuel Akinfulubi

JavaScriptBasic

Validate an email address in JavaScript

Intermediate · 4 min read

Almost every sign-up form has an email box, and almost every one checks what you type before letting you continue. The check catches typos such as a missing @ or a space in the middle. It can't tell you whether the inbox exists. Knowing that difference is half of this exercise.

In this tutorial you will write looksLikeEmail(text), a short, loose check that rejects obviously broken addresses and accepts the rest. You need to know what a string and a function are. The regular expression is explained piece by piece.

What a check can and can't do

The full rules for email addresses are long and strange. A pattern that follows every rule would be enormous, and it still couldn't tell you whether anyone reads that inbox. a@b.c is shaped like an email address and almost certainly isn't one.

So the useful design has two parts:

  1. A loose check in the form, to catch typos while the person is still typing.
  2. A confirmation email with a link. If they click it, the address is real. That is the only true validation.

This exercise builds part 1.

A regular expression in five pieces

A regular expression, or regex, is a pattern that text either matches or doesn't. test(text) returns true or false. The pattern for "something, an @, something, a dot, something" is:

Output

^[^\s@]+@[^\s@]+\.[^\s@]+$

Read it left to right:

  • ^ means "the start of the text" and $ means "the end", so the whole text must match, not just part of it.
  • [^\s@]+ means "one or more characters that are not whitespace and not @". Inside square brackets, ^ means "not", and \s means any whitespace.
  • @ is a literal at sign.
  • \. is a literal dot. A plain . means "any character", so it needs a backslash.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

49 Validate an email address, honestly

fair

Check whether text looks like an email address. Then explain why any such check is a rough filter rather than validation.

Stuck? Three hints, smallest first
  1. 1. A fully correct email regex is thousands of characters long and still cannot tell you the address exists.
  2. 2. A pragmatic check is: something, an @, something, a dot, something.
  3. 3. The only real validation is sending a message and seeing whether it arrives.

Step 1: test the pattern

In JavaScript, a regex goes between slashes:

Step 1

const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(pattern.test('amaka@example.com')); // true
console.log(pattern.test('no-at-sign.com'));    // false
console.log(pattern.test('two@@example.com'));  // false
console.log(pattern.test('missing@dot'));       // false

Two @ signs fail because the part after the first @ can't contain another one. missing@dot fails because there is no dot after the @.

Step 2: allow real-world addresses

People use dots in their names, plus signs for filtering (chidi+bookings@...), and domains with several dots. The loose pattern allows all of them, because it only bans whitespace and extra @ signs:

JavaScript

const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(pattern.test('chidi.eze+bookings@bus.example.co.uk')); // true
console.log(pattern.test('spaces in@example.com'));                // false

A stricter pattern that only allows letters and digits before the @ would reject the first address, which is a real kind of address. Rejecting a real customer is worse than letting a typo through, because the confirmation email will catch the typo anyway.

Step 3: trim, and refuse things that aren't text

People often paste an address with a space at the end. Treat that as a slip, not an error: trim() removes spaces from both ends. And if the value isn't a string at all, null.trim() would crash, so check the type first:

Step 3

const looksLikeEmail = (text) =>
  typeof text === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text.trim());
console.log(looksLikeEmail('  amaka@example.com  ')); // true
console.log(looksLikeEmail(''));                      // false
console.log(looksLikeEmail(null));                    // false

&& stops as soon as the left side is false, so for null the trim() never runs.

Step 4: see what slips through

JavaScript

const looksLikeEmail = (text) =>
  typeof text === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text.trim());
console.log(looksLikeEmail('a@b.c')); // true

This is accepted, and it is very unlikely to be a real inbox. That isn't a bug in the pattern. It is the limit of any pattern, which is why the confirmation email exists.

The full solution

The answer panel has looksLikeEmail and prints the result for seven sample addresses, then shows a@b.c being accepted. The checks cover plus tags, double @, spaces, a missing dot, trimming and a non-string value. Press Run to see the output.

The answer

// Deliberately loose. Rejects the obviously broken and accepts the rest.
const looksLikeEmail = (text) =>
  typeof text === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text.trim());

const samples = [
  'amaka@example.com',
  'chidi.eze+bookings@bus.example.co.uk',
  'no-at-sign.com',
  'two@@example.com',
  'spaces in@example.com',
  'missing@dot',
  '',
];

for (const s of samples) {
  console.log(JSON.stringify(s).padEnd(38), looksLikeEmail(s));
}

// What the check cannot tell you:
console.log('');
console.log('accepted, but almost certainly not a real inbox:', looksLikeEmail('a@b.c'));

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('an ordinary address', looksLikeEmail('amaka@example.com'), true);
test('a plus tag and multiple dots', looksLikeEmail('chidi.eze+bookings@bus.example.co.uk'), true);
test('no at sign', looksLikeEmail('no-at-sign.com'), false);
test('two at signs', looksLikeEmail('two@@example.com'), false);
test('spaces', looksLikeEmail('spaces in@example.com'), false);
test('no dot in the domain', looksLikeEmail('missing@dot'), false);
test('empty text', looksLikeEmail(''), false);
test('surrounding spaces are trimmed, not rejected', looksLikeEmail('  amaka@example.com  '), true);
test('a non-string is refused rather than crashing', looksLikeEmail(null), false);
test('it accepts things that are not real inboxes', looksLikeEmail('a@b.c'), true);

The last assertion is deliberate and is the lesson. a@b.c passes every regex you might write and is not a real address. Fully validating email syntax needs a monster of a pattern that still tells you nothing about deliverability, so the useful design is a loose filter to catch typos, then a confirmation message to do the actual validating. Note the typeof guard too: without it, looksLikeEmail(null) throws instead of returning false.

Common mistakes

  • Leaving out ^ and $. Without them the pattern only needs to match part of the text, so 'hi amaka@example.com there' passes.
  • Writing . instead of \.. A plain dot matches any character, so missing@dot passes: d fills the part before the dot, the . matches o, and t fills the end.
  • Making the pattern strict. Banning plus signs or long domain endings rejects real people. Keep it loose and confirm by email.

Try it yourself

  1. Show "Please check your email address" under a form field when looksLikeEmail is false.
  2. Write domainOf(email) that returns the part after the @, like 'example.com'.
  3. Lowercase the domain part only, so 'Amaka@Example.COM' becomes 'Amaka@example.com'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.