Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation with fields that are added to the form dynamically

I have following form:

<form class="form-validation">
  <input name="product[0][name]" id="form_product[0][name]" data-rule-required="true">
</form>

which is validated with jQuery validation plugin. I call it like this:

$(".form-validation").validate();

Validation works as expected. Then I have a button which dynamically adds fields to the form, basically it creates this:

<form class="form-validation">
  <input name="product[0][name]" id="form_product[0][name]" data-rule-required="true">
  <input name="product[1][name]" id="form_product[1][name]" data-rule-required="true">
  <input name="product[2][name]" id="form_product[2][name]" data-rule-required="true">
  ...
</form>

Now after this validation does not behave OK anymore. It still validates form but I get strange results. Sometimes onsubmit value from filed3 is moved to field2, and rules are passed between fields as well...

I think I would need to tell validator that new fields have been added, but I don't know how?

like image 738
Primoz Rome Avatar asked Oct 05 '22 12:10

Primoz Rome


1 Answers

To apply rules to dynamically created fields, you would call the rules('add') method immediately after you create the new input fields. Since you didn't show any of the code that adds the new fields, I cannot show you an exact demo of this technique.

HOWEVER, since your rules are already part of the HTML attributes, this demo below shows that your code should already be working fine:

http://jsfiddle.net/WVbmj/


Quote OP:

It still validates form but I get strange results. Sometimes onsubmit value from filed3 is moved to field2, and rules are passed between fields as well.

That's probably because you have a duplicate id, id="form_product[1][name]", on your second & third input elements. id's must be unique or you'll get strange results like this. Fix this problem like I did in the demo above.

Again, it's working when this id problem is fixed: http://jsfiddle.net/WVbmj/

like image 190
Sparky Avatar answered Oct 11 '22 06:10

Sparky