jQuery validate plugin : custom rules with dynamic element id

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

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> 

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?

回答1:

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]+" }); }); 

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

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!