jQuery validate plugin:具有动态元素id的自定义规则 [英] jQuery validate plugin : custom rules with dynamic element id

查看:65
本文介绍了jQuery validate plugin:具有动态元素id的自定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jQuery应用自定义验证规则,如下所示

I have attempted to apply a custom validation rule using jQuery as below

<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("notaccept", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
}, "<img src='../template/images/error.gif' alt='Only alphabet allowed.'>");

$("#frm1").validate({
  rules: {
    $('input[id^=txt_field]'): { 
        notaccept: "[a-zA-Z]+" }        
  }
});
});
</script>

问题是上面代码中元素前缀选择器的使用不起作用。我生成格式 txt_field11 txt_field12 等多个字段,依此类推。

The issue is the usage of element prefix selector in the above code doesn't work. I generate multiple field of the format txt_field11, txt_field12 and so on dynamically.

我可以在多个元素上应用上述验证吗?

Can I apply the above validation on multiple elements as in my case?

推荐答案

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

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.

这是一个有效的例子:< a href =http://jsfiddle.net/fDAQU/ =nofollow> 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.

这篇关于jQuery validate plugin:具有动态元素id的自定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆