Restrict Date Range in jQuery UI DatePicker for two dates

In this post, you will learn how to implement validation to "Restrict Date Range in jQuery UI DatePicker" or "End Date should be greater than Start Date by few days using jQuery Date Picker". When I say few days, which means end date must be at least StartDate + 4 or StartDate + 2.. The number can be anything depending on your requirement.

Related Post:

Following things needs to be taken care.

  1. When Start Date is selected, then need to disable all the dates before selected start date + 4 days in end date datepicker. "minDate" option is our choice here.
  2. If end date is selected first, then disable all the dates after selected end date - 4 days in Start date datepicker. "maxDate" option is our choice here.

To implement this, write code in jQuery UI Datepicker "onSelect" event which gets called when date is selected.

$(document).ready(function () {
   var daysToAdd = 4;
   $("#txtFromDate").datepicker({
      onSelect: function (selected) {
         var dtMax = new Date(selected);
         dtMax.setDate(dtMax.getDate() + daysToAdd); 
         var dd = dtMax.getDate();
         var mm = dtMax.getMonth() + 1;
         var y = dtMax.getFullYear();
         var dtFormatted = mm + '/'+ dd + '/'+ y;
         $("#txtToDate").datepicker("option", "minDate", dtFormatted);
      }
   });

   $("#txtToDate").datepicker({
      onSelect: function (selected) {
         var dtMax = new Date(selected);
         dtMax.setDate(dtMax.getDate() - daysToAdd); 
         var dd = dtMax.getDate();
         var mm = dtMax.getMonth() + 1;
         var y = dtMax.getFullYear();
         var dtFormatted= mm + '/'+ dd + '/'+ y;
         $("#txtFromDate").datepicker("option", "maxDate", dtFormatted)
      }
   });
});

The above jQuery code,

  • First, takes the selected date and converts it in Date Object.
  • And then adds/subtracts "daysToAdd" variable.
  • And it sets formatted date to Datepciker.

If you also want to make sure that Start Date should be greater than end Date then set "minDate : 0" for from date datepicker.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...