Search code examples
jqueryjquery-uidatejquery-validatejquery-ui-datepicker

Manual date entry validation for jQuery UI Datepicker maxDate option


I have jQuery datepicker on a page that needs to allow manual entry of the date, but also needs to validate that the date is no more than one day ahead. The picker control has been limited via the maxDate, but when one manually enters the date, they can enter a date more than one day ahead. How does one (me) stop that? Here is what I have so far:

$(".datepicker").attr("placeholder", "mm-dd-yyyy").datepicker({
    showOn: "button",
    maxDate: "+1",
    showOtherMonths: true
});

Solution

  • Well, the above answer is correct, but it does not validate the form, the user still will be able to submit the form,

    I have done some researches, but could not find ny, finally I wrote this function which works fine and validate the form, and does not let submit the form until the correct date is entered, Hope it helps!

    The only thing you need to do is add this code, and then this will be applied to all the fields with 'datePicker' class.

     $(".datePicker").datepicker({
                dateFormat: 'd/mm/yy',
                changeMonth: true,
                changeYear: true,
                firstDay: 1,
                minDate: Date.parse("1900-01-01"),
                maxDate: Date.parse("2100-01-01"),
                yearRange: "c-90:c+150"
            });
    
            // validation in case user types the date out of valid range from keyboard : To fix the bug with out of range date time while saving in sql 
            $(function () {
                $.validator.addMethod(
                    "date",
                    function (value, element) {
    
                        var minDate = Date.parse("1900-01-01");
                        var maxDate = Date.parse("2100-01-01");
                        var valueEntered = Date.parse(value);
    
                        if (valueEntered < minDate || valueEntered > maxDate) {
                            return false;
                        }
                        return !/Invalid|NaN/.test(new Date(minDate));
                    },
                    "Please enter a valid date!"
                );
            });