JavaScript to validate email address using a regex
Share
This is a code snippet for basic JavaScript to validate email address using a regular expression. This is building on my previous post on how to use regular expressions with jQuery. You can also load the code in jsfiddle below.
Update 12/05/13: Separated into versions for testing.
Version 1
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /^(([^<>()[]\.,;: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,}))$/igm;
if ($email.val() == '' || !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Version 2
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() == '' || !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Versions
//reported to validate incorrectly: t123@.co.in as true
/[A-Z0-9._%+-]+@[A-Z0-9-]+.+.[A-Z]{2,4}/igm
//reported to validate incorrectly: andre@uol.com@ as true
/[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm
//current version
/^(([^<>()[]\.,;: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,}))$/