JQuery Validate with custom selectors and logic

Is it possible to use jQuery Validate with custom selectors and validation logic? Something like the following:

$('#myForm').validate({ rules: { '[myattr="foo"]': function(content) { return $(content).val().contains('bar'); } } }) 

I can not find the answer to this in the documentation.

Thanks.

+4
source share
1 answer

To declare rules inside .validate() , you must use the name attribute. A workaround is to use the rules('add') method, which will allow you to use any jQuery selector. (However, despite the chosen rule assignment method, each field must still contain a unique name attribute.)

 $('[myattr="foo"]').rules('add', { required: true, messages: { required: "optional custom message" } }); 

See: http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules

Notes

  • Make sure you use the latest version of the plugin that recently fixed a bug in which using messages inside rules('add') violated the rule.

  • If your selector is like a class where you want to select more than one element, you must wrap rules('add') in jQuery .each() .

 $('.myclass').each(function() { $(this).rules('add', { required: true, messages: { required: "optional custom message" } }); }); 

To use a custom function, as a rule, you simply create your method / rule using the addMethod method and then declare it as any other rule.

  $.validator.addMethod('myrule', function(value, element, params) { // your function // return true to pass // return false to fail }, "error message"); $('#myform').validate({ rules: { myfield: { required: true, myrule: true } } }); 

See: http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

+7
source

All Articles