Reputation: 3414
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?
Upvotes: 2
Views: 10784
Reputation: 70444
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.
Upvotes: 2
Reputation: 28235
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?
Upvotes: 0