20

I am using jQuery's unobtrusive validation plugin in with ASP.NET MVC. Any fields that are rendered on the server are properly validated.

However, if I dynamically add a field in the form using JavaScript, it is not validated even though it has the appropriate HTML5 data-* attributes.

Can anyone guide me in right direction on how I can achieve this goal?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155

3 Answers3

21

Simpler Answer:

I am using MVC 4 and JQuery 1.8. I have made it to a modular function which accepts the jQuery object of the newly added element:

function fnValidateDynamicContent($element) {
    var $currForm = $element.closest("form");
    $currForm.removeData("validator");
    $currForm.removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse($currForm);
    $currForm.validate(); // This line is important and added for client side validation to trigger, without this it didn't fire client side errors.
}

For example, if you added a new table with id tblContacts, then you can invoke like this:

fnValidateDynamicContent($("#tblContacts"))
ColmanJ
  • 457
  • 2
  • 12
  • 28
Sundara Prabu
  • 2,361
  • 1
  • 21
  • 20
12

Here's a blog post you may find useful and that should put you on the right track. Extension method taken from there:

/// <reference path="jquery-1.4.4.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    //use the normal unobstrusive.parse method
    $.validator.unobtrusive.parse(selector);

    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        $('[name="' + elname + '"]').rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            $('[name="' + elname + '"]').rules("add", args);
          }
        });
      }
    });
  }
})($);

and then:

var html = "<input data-val='true' "+
           "data-val-required='This field is required' " +
           "name='inputFieldName' id='inputFieldId' type='text'/>;
$("form").append(html);

$.validator.unobtrusive.parseDynamicContent('form input:last');

Updated to add fix referenced in blog post comments, otherwise js errors occur.

Ryan O'Neill
  • 5,410
  • 4
  • 46
  • 69
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
10

In order for Darin's answer to work, I changed the following line:

$.validator.unobtrusive.parse(selector); 

To this:

 $(selector).find('*[data-val = true]').each(function(){
    $.validator.unobtrusive.parseElement(this,false);
 });

Here's the full sample:

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    // don't use the normal unobstrusive.parse method
    // $.validator.unobtrusive.parse(selector); 

     // use this instead:
     $(selector).find('*[data-val = true]').each(function(){
        $.validator.unobtrusive.parseElement(this,false);
     });
    
    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        $('[name="' + elname + '"]').rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            $('[name="' + elname + '"]').rules("add", args);
          }
        });
      }
    });
  }
})($);

$.validator.unobtrusive.parse internally calls parseElement method but each time it sends isSkip parameter to true so with this value

if (!skipAttach) {
    valInfo.attachValidation();
}

this code in jquery.unobtrusive.js does not attach validation to the element and we find only validation data of inputs that were initially present on the page.

Note Darin's answer above is correct and you can find on the blog he referred that many people have solved problem using xhalent's code (posted by darin). why it did not work is beyond my understanding. Moreover, you can find plenty of posts that tell you that just calling

$.validator.unobtrusive.parse(selector) 

is enough for dynamically loaded content to be validated

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
  • For anyone else using this, I recommend you alter one more thing about it, especially if you're using this on dynamic collections in MVC: $('[name=' + escapeAttributeValue(elname) + ']') where escapeAttributeValue does makes the name jquery selector-safe: return value.replace(/([!"#\$%&'\(\)\*\+,\.\/:;<=>\?@\[\\\]\^`\{\|\}~])/g, '\\$1'); – Zach Feb 04 '13 at 21:16
  • 3
    $.validator.unobtrusive.parse(selector) only works for a new added form. If you already have an existing form and insert new input fields to that form, it won't work. – YuMei Aug 14 '13 at 20:16