Search code examples
jqueryasp.net-mvcasp.net-mvc-3unobtrusive-validation

client side validation with dynamically added field


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?


Solution

  • 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