HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I validate an email address in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howemailvalidateaddresscanjavascript

Problem

I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?

Solution

Using regular expressions is probably the best way of validating an email address in JavaScript. View a bunch of tests on JSFiddle taken from Chromium.
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};


The following is an example of a regular expression that accepts unicode.
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;


Keep in mind that one should not rely on JavaScript validation alone, as JavaScript can be easily disabled by the client. Furthermore, it is important to validate on the server side.

The following snippet of code is an example of JavaScript validating an email address on the client side.



const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};

const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');

if(validateEmail(email)){
$result.text(email + ' is valid.');
$result.css('color', 'green');
} else{
$result.text(email + ' is invalid.');
$result.css('color', 'red');
}
return false;
}

$('#email').on('input', validate);



Enter email address

Context

Stack Overflow Q#46155, score: 6665

Revisions (0)

No revisions yet.