Explain Codes LogoExplain Codes Logo

How can I validate an email address in JavaScript?

javascript
regex
email-validation
javascript-regex
Anton ShumikhinbyAnton Shumikhin·Oct 4, 2024
TLDR

Looking for a quick solution to validate an email with JavaScript? Try applying the following regex to your code:

// "The one-liner hero", dealing with common emails like a champ const isValidEmail = email => { email = email.trim().toLowerCase(); return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email); }; // Examples console.log(isValidEmail('[email protected]')); // true console.log(isValidEmail('NotAnEmail')); // No "@"? Well, false then.

This single-line function covers the basic email structure: any non-whitespace character sequence before and after an "@", followed by a domain name after a period.

Breaking down the regex catching common emails

Regex isn't rocket science! Let's demystify this line of code:

/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/

Read as: "From the start (^), match any non-whitespace, non-@ characters ([^\s@]+), followed by "@", followed by any non-whitespace, non-@ characters ([^\s@]+) again, a dot (.), this time for the domain, and finally 2 or more non-whitespace, non-@ characters {2,} till the end ($) of the string".

We're trimming and converting the email to lowercase to ensure case insensitivity, so whether it's "[email protected]" or "[email protected]", it would all be the same here!

Digging deeper: Turbocharging your validation

While our quick solution is great for most general cases, let's crank things up a notch for advanced scenarios:

Dealing with exceptions – Unicode & new TLDs

For supporting Unicode and new TLDs (because hey, sushi is a valid TLD now), use a more comprehensive regex.

const emailRegex = /^[^\s@]+(\.[^\s@]+)*@[^\s@]+(\.[^\s@]+)+$/; // Because we love sushi. Not kidding, .sushi is a valid TLD!

I see what you did there! – Real-time validation

To give users instant feedback, the oninput event is your best friend. Remember, users love knowing when they're right (or wrong).

document.getElementById('emailInput').oninput = function() { // Green means go! Red means don't you dare hit that submit button! this.style.color = isValidEmail(this.value) ? 'green' : 'red'; };

Better safe than sorry – Server-side validation

Never underestimate the importance of server-side validation! While JavaScript lets you instantly weed out erroneous inputs, nothing beats a good old server-side check to ensure you're keeping malicious data at bay.