This is hands-down the easiest jQuery form validation that’s out there—that I’ve found anyway.
$('form.validate').submit(function() {
$(this).find('div span').remove();
$(this).find('span.error-message').hide();
var valid = true;
$(this).find(‘.req’).each(function() {
if ($(this).val() == “”) {
$(this).after(‘<span>Required!</span>’);
valid = false;
} else if ($(this).hasClass(‘req-email’) && !checkemail($(this).val())) {
$(this).after(‘<span>Invalid E-mail!</span>’);
valid = false;
} else if ($(this).hasClass(‘req-phone’) && checkphone($(this).val())) {
$(this).after(‘<span>Numbers Only!</span>’);
valid = false;
}
});
if (!valid) {
$(this).find(’span.error-message’).text(“Please correct the above errors.”).show();
return false;
}
});
function checkemail(e){
var emailfilter = /^w+[+.w-]*@([w-]+.)*w+[w-]*.([a-z]{2,4}|d+)$/i
return emailfilter.test(e);
}
function checkphone(e) {
var filter = /[0-9]/
return filter.test(e);
}
Found here: http://www.aarongloege.com/blog/web-development/javascript/jquery/easy-form-validation/
What makes it even better is that it’s highly customizable. I used Aaron’s structure to write my own custom validation. I’ve shared here the additional/modified filters.
function checkemail(e){
var emailfilter = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
return emailfilter.test(e);
}
function checkphone(e) {
var filter = /[0-9]{10}/
return filter.test(e);
}
function checkzip(e){
var zipfilter = /[0-9]{5}/
return zipfilter.test(e);
}
function checkpassword(e) {
var passwordfilter = /^.{6,50}$/
return passwordfilter.test(e);
}
function checkcreditcard(e) {
var creditcardfilter = /[0-9]{15,16}/
return creditcardfilter.test(e);
}
You can write as many of these as you want. Additionally, though he has his error messages writing to a span, you can insert whatever kind of action you want to happen inside the if/else statements.