0

I have a form with ASP MVC3, and the input fields are validated with jQuery validate plugin v1.8 (default jQuery validation with MVC3). This is working perfectly, but the problem is when I insert a new field to validate using the after or append function.

If I have this HTML:

<label for="name">Name: </label>
<input class="text-files" data-val="true" data-val-required="Name missing" id="name" name="name" type="text" value="">
<span class="field-validation-error" data-valmsg-for="name" data-valmsg-replace="true"></span>

It works OK, but if I insert it with after or insert function, it doesn't work:

$(window).load(function () {
    $('#addName').click(function (event) {
        event.preventDefault();
        var $newdiv = $('<label for="name">Name: </label><input class="text-files" data-val="true" data-val-required="Name missing" id="name" name="name" type="text" value=""><span class="field-validation-error" data-valmsg-for="name" data-valmsg-replace="true"></span>');

        $('.names').append($newdiv);
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Alberto
  • 704
  • 2
  • 12
  • 26
  • What is "doesn't work"? However, if you dynamically add a form field, you'd use the [`rules('add')` method](http://jqueryvalidation.org/rules) to apply the rules. – Sparky Aug 21 '13 at 15:55
  • Doesn´t work means that the new field is not validated. About rules(add), it doesn´t work because MVC uses unobtrusive client validation. I found the solution here: http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements – Alberto Aug 21 '13 at 22:16
  • That `unobtrusive` validation is always more of a pain than it's worth. Also, please post your actual solution below rather than just a link. It's the best way to help future readers. – Sparky Aug 21 '13 at 23:03

1 Answers1

0

The validation rules are built on elements available on DOM load. Therefore you need to use the following code to tell jQuery validate to include another field in the validation:

$('#addName').click(function (event) {
    event.preventDefault();
    var $newdiv = $('<label for="name">Name: </label><input class="text-files" data-val="true" data-val-required="Name missing" id="name" name="name" type="text" value=""><span class="field-validation-error" data-valmsg-for="name" data-valmsg-replace="true"></span>');
    $("#name").rules("add", "required"); // let validate know about the new field.

    $('.names').append($newdiv);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • That didn´t work, but I solved with this post: http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements althought I had to parse the whole form container instead of the element: $.validator.unobtrusive.parseDynamicContent('form') instead of $.validator.unobtrusive.parseDynamicContent('#name') – Alberto Aug 21 '13 at 12:22