solvit.io

Validate an email address in JavaScript using a regular expression

Solution #1

You can't validate an email address using a regular expression. The only valid solution is to send a confirmation email to your users.

Solution #2

This regular expression validates most of the real-world email addresses, but it fails with some of the edge cases allowed by the email specification:

var emailValidator = new RegExp(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i);

var isEmail = emailValidator.test('[email protected]');
Example
var result = emailValidator.test('[email protected]');
// result = true
var result = emailValidator.test('[email protected]');
// result = true
var result = emailValidator.test('user @example.org');
// result = false
var result = emailValidator.test('[email protected]');
// result = false

See the RFC 3696 for more details about the syntax of email addresses.

Find more solutions about: , , , ,