Easy jQuery Form Validation

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.

Easy Textarea Maxlength Script

This is a very simple maxlength script, quickly and easily implemented. The original is found at http://www.dynamicdrive.com/dynamicindex16/maxlength.htm


/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

Without ambition one starts nothing. Without work one finishes nothing. The prize will not be sent to you.
--Ralph Waldo Emerson

I'm a web designer and writer based out of Nashville, TN, where I live with my husband, step-daughter, and chihuahua.

moonkatcreations at gmail dot com