Dynamic jQuery Validate error messages with AddMethod based on the element

Mark Pieszak - Trilon.io picture Mark Pieszak - Trilon.io · Nov 12, 2012 · Viewed 39.1k times · Source

Let's say I have a custom AddMethod to jQuery Validate like:

$.validator.addMethod('min-length', function (val, element) {
    // do stuff

// the error message here needs to be dynamic
}, 'The field cannot be less than than '
     + element.attr('data-min') + // it is within the closure, but it can't grab it
   ' length.');

I can't figure out a way to get the element variable in question, and get any values from it. What am I missing here?

Answer

Barmar picture Barmar · Nov 12, 2012

From looking at the validator source code, I think this should do it:

$.validator.addMethod('min-length', function (val, element) {
    return this.optional(element) || val.length >= $(element).data('min');
}, function(params, element) {
    return 'The field cannot be less than than ' + $(element).data('min') + ' length.';
});

In your original code, the message string is NOT within the closure; the closure is the 2nd argument of addMethod, and the error message is the 3rd argument.