EN
TypeScript - validate email with regex
3 points
In this article, we would like to show how to validate e-mail address in TypeScript using regular expressions (RegExp
class).
The first, most important thing is: there is no one 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:
xxxxxxxxxx
1
const expression: RegExp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
2
3
const email: string = 'john@gmail.com';
4
const result: boolean = expression.test(email); // true
5
6
console.log('e-mail is ' + (result ? 'correct' : 'incorrect'));
Output:
xxxxxxxxxx
1
e-mail is correct
Google in AngularJS suggested its own expression that checks e-mail.
Note: full source code is located here.
Regular expression:
xxxxxxxxxx
1
/^(?=.{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:
xxxxxxxxxx
1
const expression: RegExp = /^(?=.{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])?)*$/;
2
3
const email: string = 'john@gmail.com';
4
const result: boolean = expression.test(email);
5
6
console.log('e-mail is ' + (result ? 'correct' : 'incorrect'));
Output:
xxxxxxxxxx
1
e-mail is correct