Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  45] [ 7]  / answers: 1 / hits: 16243  / 10 Years ago, fri, april 11, 2014, 12:00:00

I want to use jQuery Validate to validate an age is between two years in a metadata tag, and specify the years as parameters.



The problem I have is I can't pass the parameters as an object so I don't know how to access them in the error message (and can't find any documentation on it).



HTML



<input type=text name=dob id=dob validAge=[17,66] />




JavaScript



jQuery.validator.addMethod('validAge', function (value, element, params) {
value = eLifeViewModel.age();
if (value === '') {
return false;
}
var range = JSON.parse(params);
return value > range[0] && value < range[1];
}, $.format('Applicants must be older than {0} and younger than {1} years of age'));




The output for {0} is my parameter string and {1} is the HTTPInputElement.





I've now written a minAge and maxAge function to get around this, but I'd still be keen to get a resolution to this.


More From » jquery

 Answers
8

You can't find documentation, because you can't do it.



Using the jQuery Validation plugin and a custom method, you cannot declare the validAge rule inline when you need to pass parameters.



<input type=text name=dob id=dob validAge=[17,66] />


Only certain rules that can be declared with a boolean (can be declared as class names), or rules that are also HTML5 validation attributes can be declared inline.



For your custom method with parameters, it must (can) be declared within the .validate() method...



$('#myform').validate({
// your options, rules, etc,
rules: {
dob: {
validAge: [17,66]
}
}
});





EDIT:



As pointed out by @John Bubriski, this should be working. The OP was not accessing the parameters correctly in his custom method.



The OP was using JSON.parse...



var range = JSON.parse(params);


which gives a syntax error in the console since it's not recognizing params as a valid JSON string. Parsing the params variable is not necessary.



The parameters are passed into the function as params, so they can be accessed directly as params[0], params[1], etc.



jQuery.validator.addMethod('validAge', function (value, element, params) {
value = eLifeViewModel.age();
if (value === '') { // <- You do NOT need this!
/* Use the required rule instead of this conditional */
return false;
}
return value > params[0] && value < params[1];
}, $.format('Applicants must be older than {0} and younger than {1} years of age'));

[#71509] Wednesday, April 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyriquehenryq

Total Points: 248
Total Questions: 81
Total Answers: 105

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;