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?
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.