How to validate an email with Javascript
📣 Sponsor
Email validation is something that comes up again and again. Email validation is not tricky, presuming you have the right Regular Expression. Unfortunately, there are many ways to do RegEx on an email, and much of what you find on Google often eliminates valid emails, or even worse, doesn't work at all.
There is a standard Regular Expression known as RFC822, which is massive. I wouldn't recommend using that. Instead, you can use RFC5322, its successor, which is much shorter and easier to use. The function below will validate any email put into it:
const validateEmail = function(email) {
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return regex.test(email);
}
// Returns true
validateEmail('someMail@gmail.com');
Note: this is pretty full proof, but the best way to figure out if an email is valid is to send an email to it, and see what happens. This RegEx will ensure your emails are in the right format.
More Tips and Tricks for Javascript
- How to Create new Elements with Javascript
- Check if an Object Contains all Keys in Array in Javascript
- How to sort an array by date in Javascript
- How to get the Full URL in Express on Node.js
- Javascript Ordinals: Adding st, nd, rd and th suffixes to a number
- Future Javascript: Javascript Pipeline Operators
- How the Javascript History API Works
- How to validate an email with Javascript
- A Look at the New Array Methods coming to Javascript
- How to get the last element of an Array in Javascript