Validate that end date is greater than start date with jQuery
Little late to the party but here is my part
Date.parse(fromDate) > Date.parse(toDate)
Here is the detail:
var from = $("#from").val();
var to = $("#to").val();
if(Date.parse(from) > Date.parse(to)){
alert("Invalid Date Range");
}
else{
alert("Valid date Range");
}
Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers
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())
|| (Number(value) > Number($(params).val()));
},'Must be greater than {0}.');
To use it:
$("#EndDate").rules('add', { greaterThan: "#StartDate" });
or
$("form").validate({
rules: {
EndDate: { greaterThan: "#StartDate" }
}
});
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
That should do it I think
Reference jquery.validate.js and jquery-1.2.6.js. Add a startDate class to your start date textbox. Add an endDate class to your end date textbox.
Add this script block to your page:-
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('.startDate').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
$('#formId').validate();
});
</script>
Hope this helps :-)