具有动态添加字段的客户端验证

发布于 2024-11-06 15:42:51 字数 176 浏览 5 评论 0原文

我在 ASP.NET MVC 中使用 jQuery 的非侵入式验证插件。服务器上呈现的任何字段都经过正确验证。

但是,如果我使用 JavaScript 在表单中动态添加字段,即使它具有适当的 HTML5 data-* 属性,它也不会被验证。

谁能指导我如何实现这一目标的正确方向?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

东走西顾 2024-11-13 15:42:51

更简单的答案:

我正在使用 MVC 4 和 JQuery 1.8。我已将其设置为一个模块化函数,它接受新添加元素的 jQuery 对象:

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.
}

例如,如果您添加了一个 id 为 tblContacts 的新表,那么您可以调用像这样:

fnValidateDynamicContent($("#tblContacts"))

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"))
三月梨花 2024-11-13 15:42:51

这是一篇博客文章,您可能会觉得有用,应该让你走上正轨。扩展方法取自那里:

/// <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);
          }
        });
      }
    });
  }
})($);

然后:

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');

更新以添加博客文章评论中引用的修复,否则会发生js错误。

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.

海之角 2024-11-13 15:42:51

为了让达林的答案起作用,我更改了以下行:

$.validator.unobtrusive.parse(selector); 

为此:

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

这是完整的示例:

(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 内部调用 parseElement 方法,但每次发送 isSkip< /code> 参数设置为 true,因此使用此值时,

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

jquery.unobtrusive.js 中的此代码不会将验证附加到元素,我们只找到最初出现在页面上的输入的验证数据。

注意 Darin上面的回答是正确的,你可以在他提到的博客上找到很多人已经使用xhalent的代码(由darin发布)解决了问题。为什么它不起作用超出了我的理解。此外,您可以找到大量帖子来说明您认为只需调用

$.validator.unobtrusive.parse(selector) 

就足以验证动态加载的内容

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文