HTML5, CSS3, jQuery, JSON, Responsive Design...

Dynamic form validation with jQuery

Michael Brown   July 19 2013 04:20:00 AM
I've been using the superb jQuery Validation Plugin for a number of years now, and really, I don't know how I got by without it before.

Basically, it allows you to (relatively) easily set up form validation notifications that appear on the form itself - e.g. if a field needs a value, then some (usually red coloured) text will appear next to the that field, telling you so.  Here's some examples of how the plugin works.

I see so much old code - and not so old code, for that matter - where the programmer seems to think that users like nothing better than dismissing alert() dialogs when filling forms.  And when they've dismissed the first one, they click on the Submit button again, only to run into the next dialog, telling them that they've failed in their duty (missed another field) yet again.  Repeat and rinse, ad infinitum.

A project that I've been working on recently has caused me to stretch the plugin even further, and thankfully, it was well up to the job.  The requirement for this new project was that the form fields required would change, according to what options the user had selected further up the form.  Dynamic rules, in other words.  Here's a jsfiddle demo of what I mean.

On this simple form, I've set up three text fields that might require validation.  Above them is a radio option field.  If the first radio button option is checked, then one of the three text fields is required for validation.  If the second radio button option is selected, then two of three of those fields are required.  Click on the Submit button, and the validation messages, to the right of the fields, will change according to which radio button you have checked.  Not only that, but those validation messages should then disappear when you've entered something into the requisite number of fields: one or two, as the case may be.

This post on stackoverflow helped me approach this problem.  In particular, Ryley's answer gave me the require_from_group2 add-on method for the jQuery Validate plug-in, and also the addRules() and removeRules() functions.

The key to how it works is the rulesConfigObj object.  Within this object I've set up what I call "rule groups" - "oneOfTwo" and "twoOfThree" - each of which contains the jQuery Validation parameters that I want set at a particular time.  When the radio button is clicked, its jQuery.change() event does two things.  First, it removes any existing rule groups from the jQuery Validation plugin - via the removeRulesGroup() function, which is my own contribution (although it's really just a wrapper around removeRules()).  Second, it adds the appropriate rule group, "oneOfTwo" or "twoOfThree", depending on what the user picked on the radio button.

Read through the code on the JSFiddle and you should be able to follow the rest.
No Comments Found