How to customize error message of maxlength with jQuery validate to show number of entered characters

Michael Klement picture Michael Klement · Jul 30, 2009 · Viewed 9.7k times · Source

I want the maxlength validation of jQuery validate to display an error message like the following:

"Please enter no more than {0} characters. You've currently entered {1} characters."

Where {1} is a placeholder for the actual amount. What's the best way to do this?

Answer

RaYell picture RaYell · Jul 30, 2009

I don't think there is a simple way to do that but I found a workaround for you. I guess you could write your own validator for that field but this may be simpler.

Start by changing the default message for maxlength errors:

$.extend($.validator.messages, {  
    maxlength: $.validator.format("Please enter no more than {0} characters. You've currently entered CHARS_NO characters.")
});

Keep the validation as usual, but add this function:

$('input').keyup(function () {
    var rules = $(this).rules();
    if (rules.maxlength !== undefined && !$(this).valid()) {
        var errorLabel = $('label[for=' + $(this).attr('id') + '][generated=true].error');
        errorLabel.text(errorLabel.text().replace('CHARS_NO', $(this).val().length));
        return false;
    }
});

Here's the working demo for you.