February 11th, 2010
Simple jQuery Form ValidationLet’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.
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.
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. ![]() Post a Comment
|







