views:

652

answers:

2

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?

A: 

I'm not sure how you're triggering the validation, but the maxlength attribute on an input will preclude the user from entering more characters than whatever that value indicates. So, it won't be necessary to inform the user that they've entered more characters than maxlength since they simply can't do it.

Can you provide additional context and/or details?

inkedmn
It's used in an textarea where there is no way to limit the actual amount of characters you can enter. Also note that I'm using the validate plug-in for jQuery.
Michael Barth
+2  A: 

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.

RaYell
I'll try that, thanks! :)
Michael Barth