使用类而不是名称值进行 jQuery 验证

发布于 2024-08-31 16:48:34 字数 812 浏览 2 评论 0原文

我想使用 jquery 验证插件验证表单,但我无法在 html 中使用“名称”值 - 因为这是服务器应用程序也使用的字段。 具体来说,我需要限制从组中选中的复选框的数量。 (最多 3 个。)我见过的所有示例都使用每个元素的 name 属性。我想做的是使用该类,然后为此声明一个规则。

html

这有效:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation"  value="1" />

这不起作用,但这是我的目标:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" />

javascript:

var validator = $(".formToValidate").validate({    
    rules:{     
    "salutation":{  
             required:true,  
        },  
        "checkBox":{  
             required:true,  
          minlength:3  }  
   }   
});

是否可以做到这一点 - 是有没有一种方法可以在规则选项中定位类而不是名称?或者我必须添加自定义方法?

干杯, 马特

I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app.
Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.

html

This works:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation"  value="1" />

This doesn't work, but is what I'm aiming for:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" />

javascript:

var validator = $(".formToValidate").validate({    
    rules:{     
    "salutation":{  
             required:true,  
        },  
        "checkBox":{  
             required:true,  
          minlength:3  }  
   }   
});

Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?

Cheers,
Matt

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

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

发布评论

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

评论(10

断舍离 2024-09-07 16:48:34

您可以使用 .rules("add 基于该选择器添加规则", options),只需从验证选项中删除您想要基于类的任何规则,然后调用 $(".formToValidate").validate({... });,这样做:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});

You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});
笔落惊风雨 2024-09-07 16:48:34

另一种方法是使用addClassRules
它是特定于类的,而使用选择器和 .rules 的选项更通用。

调用 Use 之前

$(form).validate()

在像这样

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

: Ref: http://docs.jquery.com/Plugins/Validation/Validator/ addClassRules#namerules

对于这样的情况,我更喜欢这种语法。

Another way you can do it, is using addClassRules.
It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

你如我软肋 2024-09-07 16:48:34

我知道这是一个老问题。但我最近也需要同样的问题,我从 stackoverflow 得到了这个问题 + 这个博客的另一个答案。博客中的答案更加直接,因为它专门针对这种验证。以下是具体操作方法。

$.validator.addClassRules("price", {
     required: true,
     minlength: 2
});

此方法不需要您在此调用之上具有验证方法。

希望这对将来的人也有帮助。来源此处

I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.

$.validator.addClassRules("price", {
     required: true,
     minlength: 2
});

This method does not require you to have validate method above this call.

Hope this will help someone in the future too. Source here.

晌融 2024-09-07 16:48:34

这是使用 jQuery 的解决方案:

    $().ready(function () {
        $(".formToValidate").validate();
        $(".checkBox").each(function (item) {
            $(this).rules("add", {
                required: true,
                minlength:3
            });
        });
    });

Here's the solution using jQuery:

    $().ready(function () {
        $(".formToValidate").validate();
        $(".checkBox").each(function (item) {
            $(this).rules("add", {
                required: true,
                minlength:3
            });
        });
    });
一腔孤↑勇 2024-09-07 16:48:34

这是我的解决方案(不需要 jQuery...只需要 JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

将其放在 末尾的脚本块中,该代码段将发挥其魔力,限制签入的复选框数量最多三个(或您指定的任何数字)。

在这里,我什至会给你一个测试页(将其粘贴到文件中并尝试):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>
别低头,皇冠会掉 2024-09-07 16:48:34

因为对我来说,有些元素是在页面加载时创建的,有些是由用户动态添加的;我用它来确保一切保持干燥。

提交时,找到类 x 的所有内容,删除类 x,添加规则 x。

$('#form').on('submit', function(e) {
    $('.alphanumeric_dash').each(function() {
        var $this = $(this);
        $this.removeClass('alphanumeric_dash');
        $(this).rules('add', {
            alphanumeric_dash: true
        });
    });
});

Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.

On submit, find everything with class x, remove class x, add rule x.

$('#form').on('submit', function(e) {
    $('.alphanumeric_dash').each(function() {
        var $this = $(this);
        $this.removeClass('alphanumeric_dash');
        $(this).rules('add', {
            alphanumeric_dash: true
        });
    });
});
橘寄 2024-09-07 16:48:34

如果您想添加自定义方法,您可以

执行此操作(在本例中,至少选中一个复选框)

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" onclick="test($(this))"/>

在 Javascript 中

var tags = 0;

$(document).ready(function() {   

    $.validator.addMethod('arrayminimo', function(value) {
        return tags > 0
    }, 'Selezionare almeno un Opzione');

    $.validator.addClassRules('check_secondario', {
        arrayminimo: true,

    });

    validaFormRichiesta();
});

function validaFormRichiesta() {
    $("#form").validate({
        ......
    });
}

function test(n) {
    if (n.prop("checked")) {
        tags++;
    } else {
        tags--;
    }
}

If you want add Custom method you can do it

(in this case, at least one checkbox selected)

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" onclick="test($(this))"/>

in Javascript

var tags = 0;

$(document).ready(function() {   

    $.validator.addMethod('arrayminimo', function(value) {
        return tags > 0
    }, 'Selezionare almeno un Opzione');

    $.validator.addClassRules('check_secondario', {
        arrayminimo: true,

    });

    validaFormRichiesta();
});

function validaFormRichiesta() {
    $("#form").validate({
        ......
    });
}

function test(n) {
    if (n.prop("checked")) {
        tags++;
    } else {
        tags--;
    }
}
や三分注定 2024-09-07 16:48:34

如果您需要设置多个类规则,您可以这样做:

jQuery.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

来源: https://jqueryvalidation .org/jQuery.validator.addClassRules/

免责声明: 是的,我知道现在是 2021 年,你不应该使用 jQuery,但有时我们必须这样做。这些信息对我来说非常有用,所以我希望帮助一些最终随机的陌生人,他们必须在某个地方维护一些遗留系统。

If you need to set up multpile class rules you can do it like this:

jQuery.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

source: https://jqueryvalidation.org/jQuery.validator.addClassRules/

Disclaimer: Yes, I know it's 2021 and you shouldn't be using jQuery but, sometimes we have to. This information was really useful to me, so I hope to help some eventual random stranger who has to maintain some legacy system somewhere.

仲春光 2024-09-07 16:48:34
$(".ClassName").each(function (item) {
    $(this).rules("add", {
        required: true,
    });
});

$(".ClassName").each(function (item) {
    $(this).rules("add", {
        required: true,
    });
});

青萝楚歌 2024-09-07 16:48:34

如果您想要求一个具有特定类的命名字段,我喜欢这样做:

HTML

<form id="myForm">
    <input type="text" name="requiredField[]" class="requiredField">
    <input type="text" name="requiredField[]">
</form>

jQuery

$("#myForm").validate({
    rules: {
        "requiredField[]": {
            required: function(element) {
                return $(element).hasClass("requiredField");
            },
            normalizer: function(value) {
                return $.trim(value);
            }
        }
     }
 });

这样您就可以将其限制为以下类型的命名字段:一种形式 - 避免与其他形式的干扰 - 并且它支持动态地或在 DOM 加载之后对字段进行类更改。在此示例中,第一个字段是必需的,而第二个字段则不是必需的。

If you want to require a named field if it has a certain class, I like to do it this way:

HTML

<form id="myForm">
    <input type="text" name="requiredField[]" class="requiredField">
    <input type="text" name="requiredField[]">
</form>

jQuery

$("#myForm").validate({
    rules: {
        "requiredField[]": {
            required: function(element) {
                return $(element).hasClass("requiredField");
            },
            normalizer: function(value) {
                return $.trim(value);
            }
        }
     }
 });

That way you can limit it to the named fields of one form - avoiding interference with other forms - and it supports class changes to fields dynamically, or after the DOM loads. In this example, the first field would be required, while the second one would not be.

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