How to validate email in Jquery?
Change your input.email
block as this:
if (email == '') {
$('input.email').addClass('error');
$('input.email').keypress(function(){
$('input.email').removeClass('error');
});
$('input.email').focusout(function(){
$('input.email').filter(function(){
return this.value.match(/your email regex/);
}).addClass('error');
});
}
Explaination:
Add focusout action to input.email
form element, validates the email string using RFC822 standard. If it can't pass then add the 'error' class.
I have not tested this on my browser but it should work for jQuery > 1.4.
EDIT: I've removed the regex, place your favorite one there.
If you really don't want to use a plugin I've found this method to be quite good:
function validateEmail(email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( email ) ) {
return false;
} else {
return true;
}
}
JSFIDDLE
http://thejimgaudet.com/articles/support/web/jquery-e-mail-validation-without-a-plugin/
I'm currently using ketchup for form validation. There's also bassassist's plugin. Check a plugin, it will save you hours of regex-writing code.
You can use RegEx if you don't want to use any plugins.
var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(valueToTest))
// Do whatever if it passes.
else
// Do whatever if it fails.
This will get you most emails. An interesting read about validating emails with RegEx.
You can test the script here: http://jsfiddle.net/EFfCa/