I wrote an additional method for jquery validation plugin that checks if a given value meets the length requirements defined along with the validation process.
So the method looks like this:
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, jQuery.format("Value must have {0} characters"));
It works but the only problem is that message sent to the user doesn't meet my needs. The reason why is because one field might have more than 1 valid length.
A bank code can have 8 or 11 digits. So, if I define the options below I expect the following output in case of error: "Please, the value must have 8 or 11 digits."
{
"options":{
"rules": {
"inputx": {
"required": true,
"exactLength": [8,11]
}
}
}
}
But I want more flexibility because i can have 2 values defined as valid lengths, "Please, the value must have 8, 11, xxx or 23 digits" Or i can basic field where the input must have only 1 specific length "please, the value must have 8 digits"
So, inside the method is it possible to tell want should be passed to the message?
EDIT:
Added full solution based on Arun P Johny answer
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, function(param, element){
var str = "";
if ($.isArray(param)){
var paramLen = param.length,
lastParamValue = param[ paramLen - 1];
if (paramLen == 2){
str = param[0];
} else {
for(var i = 0; i< paramLen - 1; i++){
if (i == paramLen - 1){
str += ',' + param[i];
} else {
if (i == 0)
str += param[0];
else
str += ',' + param[i];
}
}
}
return jQuery.format("Value must have {0} or {1} characters", str, lastParamValue );
} else {
return jQuery.format("Value must have {0} characters", param )
}
});