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
});
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.
inside the jQuery script code just paste the code. $( ". selector" ). datepicker({ dateFormat: 'yy-mm-dd' });
Syntax: $(". selector"). datepicker( {defaultDate:"+6"} );
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With