I wrote a blog post explaining how to dynamically add input to a form and at the same time add validation rules for the jQuery Validate plugin.
In my example, this was an order form for helmets:
//Each set of helmet inputs gets unique IDs function newHelmetInputs(i){ var inputSet = ''; inputSet += '<label for="helmet'+ i +'color">Helmet '+ i +' Color</label>' inputSet += '<input id="helmet'+ i +'color" name="helmet['+ i +'][color]"/>' inputSet += '<label for="helmet'+ i +'size">Helmet '+ i +' Size</label>' inputSet += '<input id="helmet'+ i +'size" name="helmet['+ i +'][size]"/>' return inputSet; } //Actually adding them to the page $('#addhelmet').click(function(){ var i = nextNumber(); //nextNumber() is a closure - see my blog for details var newInputs = newHelmetInputs(i); //i is used above in IDs $(this).before(newInputs); ('#helmet' + i + 'size').rules('add', {digits: true}); //matching validation rule });
The blog post is described in more detail and also explains how to handle this using PHP.
Regarding the requirement that at least two text fields be filled, I wrote for him a jQuery validation method and a similar one that says: "either fill in at least X fields in this section, or skip the section completely."
So, for example, if your form allows people to order sandwiches, and each sandwich has an entrance for bread and filling, you can dynamically add fields for as many sandwiches as they want to order. They don’t need to fill anything with a No. 2 sandwich, but if they do, they should give you both the bread and the type of filling.
source share