Limit Date Range for "From Date" & "To Date" Date Picker Fields

Introduction

To ensure users select valid date ranges in forms, you can set restrictions on the "From Date" and "To Date" Date Picker fields. This script will ensure that both dates do not fall before the current date and that the "To Date" is always later than the "From Date."

How does it work?

This script sets the minimum date for both Date Pickers to today’s date. It also ensures that the "From Date" cannot be later than the "To Date" and vice versa. The onSelect event updates the date range based on the selected date and the function setDateRange is used to dynamically adjust the date limits of each field. Follow the steps below:

  1. Replace "fromDate" and "toDate" with the actual field names of your Date Picker fields.
  2. Add the following script to your form's custom HTML section:
    <script>
    var startDateFieldName = "fromDate";
    var endDateFieldName = "toDate";
     
    $(document).ready(function(){
            $.datepicker.setDefaults({
                    onSelect: function( selectedDate ) {
                            setDateRange(this, selectedDate);
                    }
            });
            setTodayDate();
    });
     
    //set the date limit based on value. If does not present, set to current date.
    function setTodayDate(){
            var date1_string = $("[name="+startDateFieldName+"]").val();
            var date2_string = $("[name="+endDateFieldName+"]").val();
     
            if (date1_string == "" && date2_string == ""){
                    $("[name="+startDateFieldName+"], [name="+endDateFieldName+"]").datepicker( "option", "minDate", new Date());
            } else {
                    if (date1_string != "") {
                            setDateRange($("[name="+startDateFieldName+"]"), date1_string);
                    }
                    if (date2_string != "") {
                            setDateRange($("[name="+endDateFieldName+"]"), date2_string);
                    }
            }
    }
     
    //function to set min & max date
    function setDateRange(element, selectedDate) {
            var option = $(element).attr("name") == startDateFieldName ? "minDate" : "maxDate";
            var instance = $(element).data( "datepicker" );
            var date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                $.datepicker._defaults.dateFormat
                ,selectedDate, instance.settings );
            $("[name="+startDateFieldName+"], [name="+endDateFieldName+"]").not(element).datepicker( "option", option, date );
    }
    </script>
Created by Julieth Last modified by Aadrian on Dec 13, 2024