且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery validate plugin:具有动态元素id的自定义规则

更新时间:2022-12-11 08:41:09

我不确定规则选项是否足够强大,可以接受元素的任意选择器并为这些元素应用验证规则。

I'm not sure if the rules option is powerful enough to accept an arbitrary selector for elements and apply a validation rule for those elements.

但是,您可以在初始化验证器后添加规则:

You can, however, add rules after initializing validator:

$.validator.addMethod("notaccept", function(value, element, param) {
    return value.match(new RegExp("^" + param + "$"));
}, "Only alphabet allowed");

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

$('input[id^="txt_field"]').each(function() {
    $(this).rules("add", { notaccept: "[a-zA-Z]+" });
});

.each 调用是必要的,因为它看起来像验证者只在第一个匹配的项目上调用 .rules()

The .each call was necessary because it looked like validator was only calling .rules() on the first matched item.

这是一个有效的例子: http://jsfiddle.net/fDAQU/

Here's a working example: http://jsfiddle.net/fDAQU/

我将进行更多挖掘,看看是否有办法在最初传递给验证器的选项对象中添加规则。

I'll do some more digging and see if there's a way to add rules in the options object you initially pass to validator.