Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 419
Sam Carleton Avatar asked Jun 27 '12 14:06

Sam Carleton


People also ask

What is MinDate and MaxDate in jQuery datepicker?

If you like to restrict access of users to select a date within a range then there is minDate and maxDate options are available in jQuery UI. Using this you can set the date range of the Datepicker. After defining these options the other days will be disabled which are not in a defined range.

How can change date format in jQuery UI datepicker?

inside the jQuery script code just paste the code. $( ". selector" ). datepicker({ dateFormat: 'yy-mm-dd' });

How do I change the default date in datepicker?

Syntax: $(". selector"). datepicker( {defaultDate:"+6"} );


3 Answers

I had exactly the same requirement and here is the solution that worked for me like a charm:

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

Modified fiddle here referenced from Salman A's answer

like image 84
Main Pal Avatar answered Oct 19 '22 12:10

Main Pal


One option is to remove the ability to manually enter a date by making the input fields readonly. This will restrict the user from manually entering anything crazy, and forces the use of the datepicker.

like image 27
Esten Avatar answered Oct 19 '22 11:10

Esten


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

like image 21
Salman A Avatar answered Oct 19 '22 11:10

Salman A