Manual date entry validation for jQuery UI Datepicker maxDate option

Sam Carleton picture Sam Carleton · Jun 27, 2012 · Viewed 41.6k times · Source

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
});

Answer

Salman A picture Salman A · Jun 27, 2012

I am not sure if datepicker fires an event if the control's value is changed by typing in directly. You can bind a function to the .change() event:

$(".datepicker").attr("placeholder", "mm-dd-yyyy").datepicker({
    dateFormat: "mm-dd-yy",                 // since you have defined a mask
    maxDate: "+1",
    showOn: "button",
    showOtherMonths: true

}).on("change", function(e) {
    var curDate = $(this).datepicker("getDate");
    var maxDate = new Date();
    maxDate.setDate(maxDate.getDate() + 1); // add one day
    maxDate.setHours(0, 0, 0, 0);           // clear time portion for correct results
    if (curDate > maxDate) {
        alert("Invalid date");
        $(this).datepicker("setDate", maxDate);
    }
});

Demo here