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.