Languages
[Edit]
EN

JavaScript - validate email with regex

5 points
Created by:
AnnLen
1795

In this article we would like to show how to validate e-mail address in JavaScript using regular expressions (RegExp class).

First most important thing is: there is no one way how to write expression that validatee e-mail. Some solutions are more precise in checking coorrectness, other less.

Internet is filled with different solutions, so 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'));

AngualrJS expression example

Google in AngualrJS suggested 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'));

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.