In this article I will explain how to implement Start Date should be less than End date validation in jQuery DatePicker.
When we use two jQuery DatePickers one for choosing the start date while other for choosing the end date, there’s a need to validate that the selected start date must always be less than the selected end date.
HTML Markup
The HTML Markup consist of HTML Table consisting of two TextBoxes one for selecting the Start (From) date while other for selecting the End (To) date.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
From:
</td>
<td>
<input type="text" id="txtFrom" />
</td>
<td>
</td>
<td>
To:
</td>
<td>
<input type="text" id="txtTo" />
</td>
</tr>
</table>
Implement Start Date should be less than End date validation in jQuery DatePicker
Inside the jQuery document ready event handler, I am applying the jQuery DatePicker plugins to both the TextBoxes.
Inside the onSelect event handler of the Start Date jQuery DatePicker, the selected date is fetched and a day is added to the selected Start Date and then the date is set as Minimum Date for the End Date jQuery DatePicker using the minDate option.
This makes the Start Date and the dates before the Start Date disabled in the End Date jQuery DatePicker.
In similar way inside the onSelect event handler of the End Date jQuery DatePicker, the selected date is fetched, but now instead of adding we will subtract a day from the selected End Date and then set the date as Maximum Date for the Start Date jQuery DatePicker using the maxDate option.
This makes the End Date and the dates after the End Date disabled in the Start Date jQuery DatePicker.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="Stylesheet"type="text/css"/>
<script type="text/javascript">
$(function () {
$("#txtFrom").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() + 1);
$("#txtTo").datepicker("option", "minDate", dt);
}
});
$("#txtTo").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() - 1);
$("#txtFrom").datepicker("option", "maxDate", dt);
}
});
});
</script>
Screenshots
Start Date and dates before Start Date disabled while selecting End Date
End Date and dates after End Date disabled while selecting Start Date
Demo
Downloads