How to Set Minimum and Maximum Date in jQuery UI Datepicker

While using jQuery UI Datepicker in your project you want to allow users to select only days between your specified date range.

jQuery UI Datepicker has two options – minDate, and maxDate that allow you to specific date range to your Datepicker.

It simply disables other days which are not between the defined range.

In this tutorial, I show you how to use both options in your jQuery UI Datepicker.

How to Set minimum and maximum date in jQuery UI Datepicker


Contents

  1. maxDate
  2. minDate
  3. Example
  4. Demo
  5. Conclusion

1. maxDate

This option allows defining maximum possible date selection after that dates are not selectable in the widget. Its default value is null that means there is no maximum date.

You can define option value in three ways –

  • Date Object – A date object containing the maximum date.
  • Number – Number of Days from Today. For example – if you have specified 5 then the maximum is set to the next 5 days from today, in case if you specify -5 that means earlier 5 days from today.
  • String – You need to pass value in specified format. "y" for "year", "m" for "month",  "w" for "week", and "d" for "days". i.e. "+1m", "+1m+2w"

Example –

$(document).ready(function(){
 // Date Object
 $('#datepicker1').datepicker({
  dateFormat: "yy-mm-dd",
  maxDate: new Date('2016-12-26')
 });

 // Number
 $('#datepicker2').datepicker({
  dateFormat: "yy-mm-dd",
  maxDate: 2
 });

 // Number
 $('#datepicker3').datepicker({
  dateFormat: "yy-mm-dd",
  maxDate: "+1m"
 });
});

Output 


2. minDate

This option set minimum possible date selection to your Datepicker widget. Its default value is also null.

It takes values in any of the forms – Date Object, Number, and String same as maxDate.

Example –

$(document).ready(function(){
 // Date Object
 $('#datepicker1').datepicker({
  dateFormat: "yy-mm-dd",
  minDate: new Date('2016-11-2')
 });

 // Number
 $('#datepicker2').datepicker({
  dateFormat: "yy-mm-dd",
  minDate: -3
 });

 // Number
 $('#datepicker3').datepicker({
  dateFormat: "yy-mm-dd",
  minDate: "-3w"
 });
});

Output


3. Example

Using both maxDate and minDate options.

I am using String and Number value in options and set maxDate to 1 month 10 days from today and minDate to 10 days earlier.

<script type='text/javascript'>
$(document).ready(function(){

 $('#datepicker').datepicker({
  dateFormat: "yy-mm-dd",
  maxDate:'+1m +10d',
  minDate: -10

 });

});
</script>

<div class='container'>
 <input type='text' id="datepicker" /> 
</div>

4. Demo

Click on the Textbox.


5. Conclusion

This restricts the user from the day selections in your form. You can also use Number and String define format to specify options value.

You can use either both or anyone of the options in your project.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *