基于循环中的数据属性添加jQuery验证规则

Wes*_*rch 6 javascript jquery jquery-validate

我正在使用jQuery验证插件尝试添加基于data-属性的规则.我正在添加基于data-minlength或的最小/最大长度规则data-maxlength.这是一些示例HTML:

<form>
    <input name="input1" data-maxlength="5" data-minlength="3" required>
    <input name="input2" data-maxlength="5" required>
    <input name="input3" data-minlength="3" required>
    <button>Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我这样做是为了添加规则,它工作正常:

$('input[data-minlength]').each(function(){
    if ($(this).data('minlength')) {
        $(this).rules("add", {
            minlength: $(this).data('minlength')
        });
    }
});

$('input[data-maxlength]').each(function(){
    if ($(this).data('maxlength')) {
        $(this).rules("add", {
            maxlength: $(this).data('maxlength')
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

但我想缩短它,所以我尝试了这个并且它不起作用:

['minlength', 'maxlength'].forEach(function(item){
    $('input[data-'+item+']').each(function(){
        if ($(this).data(item)) {
            // alert(item) shows the correct rule name
            $(this).rules("add", {
                // Next line fails, but hardcoding a rule name works
                item: $(this).data(item)
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

错误是因为$.validator.methods[method]未定义.不知何故,它传递给它的方法名称错误,即使alert(item)告诉我规则名称是正确的.

有没有人知道为什么,或者有一个替代解决方案,我可以用来缩短上面的重复,工作代码?

演示:http://jsfiddle.net/kaVKe/1/

BNL*_*BNL 6

它不起作用,因为您正在使用名为item的新属性创建对象文字.

这个怎么样?

['minlength', 'maxlength'].forEach(function(item){
    $('input[data-'+item+']').each(function(){
        if ($(this).data(item)) {
            // alert(item) shows the correct rule name
            var options = {};
            options[item] = $(this).data(item);

            $(this).rules("add", options);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

这将创建一个options对象并添加您需要的适当属性.


Yos*_*shi 5

尝试:

['minlength', 'maxlength'].forEach(function(item){
    $('input[data-'+item+']').each(function(){
        if ($(this).data(item)) {
            var rule = {};
            rule[item] = $(this).data(item);
            $(this).rules("add", rule);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

您的解决方案不起作用,因为在对象文字表示法中,属性名称不会被解释为变量:

{
  item: ... // <-- this one
}
Run Code Online (Sandbox Code Playgroud)