Let's face it. Form validation is about as much fun as playing tic-tac-toe against yourself. It is a dull task that has to be done but really isn't that much fun. Mostly it's just a thousand "if" statements. Of course, the bigger the form the bigger the pain.

jQuery to the rescue.

While there are lots of great jQuery plugins for form validation, you can do it simply without any of them. If form validation is complex, a plugin might be useful, but for things like "contact us" forms or forms with lots of text inputs but no complexity then this method works great.

First let's do some HTML.

<form action="/the/target/file.php" method="post" id="form1" onsubmit="return checkForm();"> <label for="field1" class="reqtext">Form Label 1</label> <input type="text" name="field1" class="req" /> <label for="field2" class="reqtext">Form Label 2</label> <input type="text" name="field2" class="req" /></form>Notice the two CSS classes placed within the tags. These two classes, "reqtext" and "req" are the jQuery identifiers we will use to discover and then check each input field. Also notice that we put in an "onsubmit" element in the form tag. I like to use these instead of the jQuery.submit(). You can work either way. I'm just more comfortable with this format. Here's the jQuery statements.

function checkForm() { // Initialize our error flag var error = false; // Cycle through the tags with the CSS class "req" in them. $('.req').each(function() { if($(this).val==()) { error = true; } }); // If the error flag is set, set the titles for all required fields to a // nice shade of red to let them know which fields are required. if(error) { $('.reqtext').css("color","#922"); return false; // don't submit the form } else { return true; }}Let's work through the "checkForm()" function. First we set a flag to record if we have errors. Second we iterate through all the form fields with the CSS class "req". If they don't have any text in them, it sets the "error" flag. Lastly, after we finish checking things we provide the user with whatever visual feedback we think is required. In this case we set the text color for all the elements with the CSS class "reqtext" to red. You can take the last step as far as you want.

So there you go. A quick and simple validation that can be used for small forms and large forms alike. It allows you to validate what you want and leave the rest alone. Happy validating.