Form validation tips and tricks using jQuery

Line Break

Author: Mohannad Hussain (9 Articles)

Hello, my name is Mohannad! I am a Zend certified PHP 5 engineer, but I am also interested in Javascript, Java, mobile development (native & web), Linux & shell scripting plus User experience & interface.

I’ll keep this article short and sweet… I love jQuery! The end.

Just kidding! I do love jQuery though. Recently I have written a quick and nice (in my opinion at least) Javascript function to do simple form validation on the client side for me. I am not including the whole function here because I am sure others have posted better solutions online, but I will include the part I thought was cool, thanks to jQuery.

First, a bit of background. My function is invoked upon form submission and expetcted to return true or false, obviously. I am currently passing the list of field ids to it using a global array variable. So I loop through the array to do my checks, and for the ones that don’t pass my validation, I do this:

$('label[for="'+elemId+'"]').attr('class','error');
missing[missing.length] = $('label[for="'+elemId+'"]').text();

Where “missing” is an array I declared within my function, and class “error” is a CSS class with extra styling to make the label stand out, in my case that extra styling is a simple “color: red”. As you may have noticed, this will only work if your form has proper markup, namely if fields have unique ids each, and labels are properly linked to them using the “for” attribute.

Lastly, at the bottom I have:

if( missing.length > 0 ) {
alert("You missed filling out the following required fields:\n- "+missing.join("\n- "));
return false;
}
return true;

You can easily change it so the error message shows up in an existing div you have for that purpose, instead of using alert as I did in my example.

That’s all, I hope someone finds that useful!