client side validation with dynamically added field

后端 未结 3 1407
盖世英雄少女心
盖世英雄少女心 2020-12-05 01:11

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

3条回答
  •  臣服心动
    2020-12-05 01:30

    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

提交回复
热议问题