Validate email address textbox using JavaScript
This is quite an old question so I've updated this answer to take the HTML 5 email type into account.
You don't actually need JavaScript for this at all with HTML 5; just use the email input type:
<input type="email" />
If you want to make it mandatory, you can add the required parameter.
If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, e.g.:
<input type="email" pattern="[email protected]" />
There's more information available on MozDev.
Original answer follows
First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/
It's pretty comprehensive - :
^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$
I think you want a function in your JavaScript like:
function validateEmail(sEmail) {
var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;
if(!sEmail.match(reEmail)) {
alert("Invalid email address");
return false;
}
return true;
}
In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like:
<input type="text" name="email" onblur="validateEmail(this.value);" />
Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier.
Note: I tend to use the match()
string method rather than the test()
RegExp method but it shouldn't make any difference.
Assuming your regular expression is correct:
inside your script tags
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
in your textfield:
<input type="text" onblur="validateEmail(this);" />