Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to validate an email address

Short answer

A simple pattern checks the main thing: something, then @, then a domain with a dot, and no spaces:

const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
 
console.log(isEmail('anna@example.com'));
console.log(isEmail('anna@example'));
console.log(isEmail('anna example@mail.com'));

Output:

true
false
false

In a form

A field with type="email" is checked by the browser itself. checkValidity() returns the result in JavaScript:

<input id="email" type="email" required placeholder="you@example.com">
<button id="check">Check</button>
<p id="out"></p>
<script>
  document.getElementById('check').addEventListener('click', () => {
    const input = document.getElementById('email');
    document.getElementById('out').textContent = input.checkValidity() ? 'OK' : input.validationMessage;
  });
</script>

Normalizing

Before checking and saving, remove spaces at the edges and convert the address to lowercase:

const email = '  Anna.Smith@Example.COM '.trim().toLowerCase();
 
console.log(email);

Output:

anna.smith@example.com

Common mistake

Do not try to write a perfect regular expression: valid addresses are too varied, and a strict pattern rejects real users. The only reliable check is to send a confirmation email. Also, check on the server again: the browser check is easy to bypass.

const tooStrict = (value) => /^[a-z]+@[a-z]+\.[a-z]{2,3}$/.test(value);
 
console.log(tooStrict('anna.smith@example.com'));
console.log(tooStrict('anna@example.travel'));

Output:

false
false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.