Using the jQuery Validation plugin to validate forms, how would you confirm that a string is exactly X characters long?
You could also make the existing rangelength
method support exact range by supplying a dynamic message like this:
$.extend($.validator.messages, {
rangelength: function(args, inputElement) {
var isExactRange, min, max;
// Cast arguments as numbers
min = Number(args[0]);
max = Number(args[1]);
isExactRange = min === max;
if (isExactRange) {
return 'Please enter exactly ' + min + ' characters.';
}
return 'Please enter between ' + min + ' and ' + max + ' characters.';
}
);
As can be seen, you can generate messages on the fly based on the arguments passed to the validation methods. Message callbacks are passed the validation method arguments as their first argument, and the input element being validated as their second argument.
This makes it possible to return one message when a exact range is specified, but another if upper and lower bounds are not the same.
To fallback to the default rangelength
message, replace
'Please enter between ' + min + ' and ' + max + ' characters.'
with
$.validator.messages.rangelength
It would be nice if the official documentation would be updated, as it is difficult to navigate in and does not describe all functionalities of the plugin.