EN
JavaScript - validate email with regex
20
points
In this article, we would like to show how to validate e-mail address in JavaScript using regular expressions (RegExp
class).
The most important thing is that there's no single way how to write an expression that validates an e-mail. Some solutions are more precise in checking correctness, others less.
Internet is filled with different solutions, so the main goal of the article is to gather all of them in one place.
Quick solution:
// ONLINE-RUNNER:browser;
var expression = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
var email = 'john@gmail.com';
var result = expression.test(email);
console.log('e-mail is ' + (result ? 'correct' : 'incorrect'));
Reusable function
In this example, we create a reusable arrow function that validates the email
passed as an argument returning true
or false
.
// ONLINE-RUNNER:browser;
const EXPRESSION = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
const validateEmail = (email) => EXPRESSION.test(email);
// Usage example:
console.log(validateEmail('john@gmail.com')); // true
AngualrJS expression example
Google in AngularJS suggested its own expression that checks e-mail.
Note: full source code is located here.
Regular expression:
/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
Working example:
// ONLINE-RUNNER:browser;
var expression = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
var email = 'john@gmail.com';
var result = expression.test(email);
console.log('e-mail is ' + (result ? 'correct' : 'incorrect'));
Output:
e-mail is correct