JQuery Validate with custom selectors and logic

javascript, jquery, jquery-validate

Solution

To declare rules inside of `.validate()`, you must use the `name` attribute. A workaround is to use the `rules('add')` method which will let you use any jQuery selector. ( However, despite the chosen method for assigning rules, every 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 which only recently fixed a bug where using `messages` inside of `rules('add')` broke the rule.

If your selector is something like a `class` where you want to select more than one element, you must wrap `rules('add')` within a 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 like 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

Problem

Is it possible to use JQuery Validate with custom selectors and validation logic? Something in the vein of the following: ``` $('#myForm').validate({ rules: { '[myattr="foo"]': function(content) { return $(content).val().contains('bar'); } } }) ``` I can't seem to find the answer to this in the documentation. Thanks.

Original source