There is no such rule or method called greaterThan
within the jQuery Validate plugin. The answer you referenced is merely using the plugin's .addMethod()
method to create a custom rule called greaterThan
.
Quote OP:
"But when I send over: EndDate: { greaterThan: "#StartDate" }
The result message is 'Must be greater than #StartDate'. I would like to do something like EndDate: { greaterThan: ["#StartDate","Start Date"] }
."
Your question is written very poorly. However, if I understood it correctly,
See the second example in the documentation, which correctly shows how to use multiple parameters within the function and error message.
Assuming you want to pass a second parameter in order to improve the error message, simply access this second parameter using {1}
within the message.
Within the function, access the first parameter using params[0]
.
In other words...
When you declare your rule with multiple parameters as in this example...
rules: {
field: {
customRule: [x,y]
}
}
Inside jQuery.validator.addMethod("customRule", function(value, element, params){...}, "message")
, the parameters are accessed as follows...
within the function:
params[0]
equals x
params[1]
equals y
within the message:
{0}
equals "x"
{1}
equals "y"
"Must be between {0} and {1}"
will display as "Must be between x and y"
Assuming the function from the linked answer is correct, apply the edits as follows...
jQuery.validator.addMethod("greaterThan", function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params[0]).val());
}
return isNaN(value) && isNaN($(params[0]).val()) || (Number(value) > Number($(params[0]).val()));
},'Must be greater than {1}.');
Declare the rule as you requested...
$("form").validate({
rules: {
EndDate: {
greaterThan: ["#StartDate","Start Date"]
}
}
});
EDIT:
Based on comments, simply check to see if the first field is empty before doing anything else...
jQuery.validator.addMethod("greaterThan", function(value, element, params) {
if ($(params[0]).val() != '') {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params[0]).val());
}
return isNaN(value) && isNaN($(params[0]).val()) || (Number(value) > Number($(params[0]).val()));
};
return true;
},'Must be greater than {1}.');