Dynamic form elements & the jQuery validation plugin
I recently run into a problem where I had to validate a form with dynamic fields. I am impressed of the jQuery Validation plugin but I had no clue on how to achieve this as the documentation does not have any code on this included. A few searches on in the WWW didn’t bring the right results, but I eventually found some snippet in the Google Groups (I forgot where, sorry).
Now, let’s say you have a form with a few elements and depending on their selection or values one or more fields are added to the form:
View a basic sample/demo form here
Since you cannot validate a hidden element (because the user can’t make a selection or enter anything), you cannot add validation rules. You need to add/remove this rules dynamic depending on the user’s input.
Actually, the code is very simple. All you have to do is to catch the ‘change’, ‘blur’ or whatever event from the ‘other’ element and attach a simple function to add the validation rule. To go with the demo form this is it:
jQuery( jQuery("input[name='howhelp']") ).change( function() { if ( jQuery("input[name='howhelp']:checked" ).val() == "help" ) { jQuery("#whathelp").rules("add", "required"); jQuery("#problems").show(); } else { jQuery("#whathelp").rules("remove", "required"); jQuery("#problems").hide(); } });
Simple. Let’s see what the code does line for line:
- line 1 tells to fire a function if the radiobuttons status have changed
- line 3 checks if the current selected radiobutton’s value is equal to ‘help’
- line 5 adds the validation rule to the hidden select ‘whathelp’
- line 6 shows the hidden select
- the rest removes the validation rule and hides the select, in this case the value was not equal to ‘help’
With this code, you can validate pretty much any complex form with the validate plugin.
Further reading:
I’d like to know how you validate complex dynamic forms, so please leave your comments here.

Cool plugin.By the way,don’t you update iF AJAX Comments For WordPress?
@Showform
There is a slight chance that I have time to update my plugin in the coming weeks.
I tried using jquery validation for a dynamic form but with multiple checkboxes.
If a checkbox is checked than a box apears under it and inside there are 3 fields. For these 3 fields i added a required rule. It works fine for the first checkbox … but for the rest of them it doesn’t work.
Did have a similar problem and a solution for it to :D.
Thanks.
maybe im confused by why don’t you just do:
childfield: {
required: “#parentfield:checked”
},
blog: webofwork.com/blog
@cookie
I didn’t knew that we can use such selectors in the ‘required’ condition. Thanks for the tip!
Cool. Very useful one!!