There are a couple of approaches depending on the rules, HTML markup and code, most of which you haven't shown.
1) If the only rule you need to apply to dynamically created elements is something simple like required
, then make sure your dynamically created elements contain the required
attribute.
<input type="text" name="dynamic_element_1" required="required" />
2) More complex rules can be applied to dynamically created elements using the plugin's .rules('add')
method inside the function that creates the new elements
$(document).ready(function() {
$('#myForm').validate({
// other rules & options
});
// function to dynamically create new elements
// create new elements
// apply the rules
$('input[name="dynamic_element_2"]').rules('add', {
required: true,
// more rules
});
// end code to create new elements
});
Notes:
1) The .rules()
method must be placed inside a jQuery .each()
if/when you're targeting more than one element at a time. Otherwise only the first element in the set will get the rule.
2) Your dynamically created elements must have unique name
attributes or the plugin will not work. If they have an id
it should also be unique to maintain valid HTML and ensure the JavaScript engine does not choke.
3) There are many possible variations on what I've shown above but without a more complete example of your actual code, it's hard to say what would work best.
4) Compound rules can also be saved in variables, or classes can be created to represent compound rules. Again, hard to say what would work best when your code remains a mystery.
Here's a more comprehensive answer about adding rules, where some of the methods (2a and 2b) will work on dynamically created elements.