This is my least favorite topic; validating email addresses. There are hundreds of examples using regular expressions that are all slightly different and all have there own quirks with them.
If validation must be done, I suggest only doing this on the client-side. Ideally the server-side performs email validation by sending an actual email that includes a unique link to validate the email is valid.
But if JavaScript is a must, here is the best one I've found.
This regular expression is taken from W3C which gives me a bit more confidence in it being as robust as possible.
Now for me personally, I'd go even simpler in literally checking for only an @ symbol because that is legitimately the bare minimum that is required in every email address.
I am aware that indexOf is zero-based so if the first value was an @ this would not pass. I'm ok with that because it also at least asserts there is a minimum of 1 character before the @.
As long as the server-side takes care of the real validation, I'm good with the most simple check possible. Published on Jan 26, 2020 Tags: validation
| JavaScript
| regex
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Regular Expression to validate email
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.
if (email.indexOf('@') > 0) {
console.log('Good enough');
}
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.