jQuery 使用动态添加字段的客户端验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5965470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:06:10  来源:igfitidea点击:

client side validation with dynamically added field

jqueryasp.net-mvcasp.net-mvc-3unobtrusive-validation

提问by Muhammad Adeel Zahid

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

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

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.

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

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

任何人都可以指导我如何实现这一目标的正确方向吗?

采纳答案by Muhammad Adeel Zahid

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

为了让 Darin 的回答起作用,我更改了以下行:

$.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.parseinternally calls parseElement method but each time it sends isSkipparameter to true so with this value

$.validator.unobtrusive.parse内部调用 parseElement 方法,但每次它发送isSkip参数为 true 所以这个值

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.

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

NoteDarin'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 poststhat tell you that just calling

注意Darin 上面的回答是正确的,你可以在他提到的博客上找到很多人使用 xhalent 的代码(由 darin 发布)解决了问题。为什么它不起作用超出了我的理解。此外,你可以找到很多帖子告诉你,只要打电话

$.validator.unobtrusive.parse(selector) 

is enough for dynamically loaded content to be validated

足以验证动态加载的内容

回答by Sundara Prabu

Simpler Answer:

更简单的答案:

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

我正在使用 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.
}

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

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

fnValidateDynamicContent($("#tblContacts"))

回答by Darin Dimitrov

Here's a blog postyou 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.

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