Reputation: 165
i saw this example : Validate that end date is greater than start date with jQuery
talking about the validation of end date greater than start, date format for my input are always mm/yyyy, so it's not working for me if : start date > 122000 end date > 012002
I think i have to split my date, to just check on yyyy, if is greater or not, but didn't know how to resolve it ... here is my code ( i want always to say that if i have not 7 characters in my input to don't pass form submit :
HTML
<input type="text" id="starddate" />
<input type="text" id="enddate" />
<div id="msg"></div>
<input type="submit" id="submit" />
JS
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params).val());
}
return isNaN(value) && isNaN($(params).val())
|| (parseFloat(value) > parseFloat($(params).val()));
},'Must be greater than {0}.');
$("#enddate").rules('add', { greaterThan: "#startdate" });
Upvotes: 1
Views: 3462
Reputation: 1074909
If your date values are strings are in the form mm/yyyy
, then you can't use new Date(value)
to create a Date
object for them — that's not a format that the Date
constructor is documented as accepting (and until recently, it wasn't documented to accept anything at all except whatever the output of toString
was, which was also up to the implementation to decide).
But the problem's not difficult: Given dateA and dateB which are strings in that format:
// Assumes the format mm/yyyy (not mmyyyy, which your example values seem to be in)
var compareA, compareB;
compareA = dateA.substring(3) + dateA.substring(0, 2);
compareB = dateB.substring(3) + dateB.substring(0, 2);
if (compareA > compareB) {
// The date represented by `dateA` is later than the date
// represented by `dateB`
}
or less clearly
if (dateA.substring(3) + dateA.substring(0, 2) > dateB.substring(3) + dateB.substring(0, 2)) {
// ...
}
E.g., you can just compare strings if you move the year before the month, because the string "200012"
is <
the string "200201"
.
Upvotes: 2