How can I validate an email address in JavaScript?
Looking for a quick solution to validate an email with JavaScript? Try applying the following regex to your code:
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.
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).
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.
Was this article helpful?