4

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.

1
  • Your specific validation logic can easily be expressed as a regex Commented Apr 1, 2013 at 18:43

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.