Search code examples
javascriptjqueryjquery-uidatejquery-ui-datepicker

How to prevent selecting date range in which there is a disabled date in between?


I have two Jquery date pickers, in which a range of dates can be selected.

I have implemented certain restrictions like, the date of textbox2 should be always greater than textbox1. In addition I have disabled certain dates.

What I need is, if a user selects from date, and then selects to date, if there exist a disabled date in between, then the user should not be able to select that range.

For example:

I have disabled the dates: "31-5-2014", "1-6-2014", "2-6-2014"

If user selects date1 as 29-5-2014, and tries to select 4-6-2014 as the second date, then he should not be able to do that as disabled dates are in betweeb. The max value for date2 must be 30-5-2014

Adding the fiddle


Solution

  • I added a function "validateDateRange" to your code to illustrate the logic required to complete this task. Please note that the intention of the function I added is to simply pop up an alert if the condition you described occurs. From here you should be able to do whatever you like. Let us know if you have more questions or were looking for something else.

    Here are my updates

    function validateDateRange() {
    
        var txtStartDate = $("#start_date");
        var txtEndDate = $("#end_date");
        var startDate;
        var endDate;
        var tempDate;
    
        if (txtStartDate.val() == "") 
            return false;
    
        if (txtEndDate.val() == "") 
            return false;
    
        startDate = new Date(txtStartDate.val());
        endDate = new Date(txtEndDate.val());
    
        for (i = 0; i < unavailableDates.length; i++) {
            var temp = unavailableDates[i].split("-");
    
            tempDate = new Date(temp[2], temp[1]-1, temp[0]);
    
            if (startDate < tempDate && endDate > tempDate) {
                alert("Invalid Date Range");
                return false;
            }
        }
    }