Dynamic jQuery Validate error messages with AddMethod based on the element

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.

Leave a Comment