You can easily enable date selection to the form element using Bootstrap datepicker if you are already using Bootstrap on your page.
You need to add an external Bootstrap datepicker library.
This allows the users to select any date from the datepicker and they are not restricted.
In this tutorial, I show how you can validate Bootstrap datepicker start and end date in Bootstrap 5.
Contents
1. Download and Include
- Download jQuery and Bootstrap.
- Also, need to download Bootstrap datepicker which you can download from here.
- Include jQuery, Bootstrap, and Bootstrap datepicker script and CSS files.
<!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" > <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" ></script> <!-- Datepicker --> <link href='bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' rel='stylesheet' type='text/css'> <script src='bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js' type='text/javascript'></script>
2. Fixed Start and End date
Pass the date in the valid format in startDate
and endDate
options while initializing.
In the example, I am setting date range between '2022-7-15'
and '2022-8-15'
.
Completed Code
<div class='container' style='margin-top: 100px;'> <input type='text' class="form-control" id='datepicker' placeholder='Select Date' style='width: 300px;' > </div> <!-- Script --> <script type="text/javascript"> $(document).ready(function(){ $('#datepicker').datepicker({ format: "yy-mm-dd", startDate: new Date('2022-7-15'), endDate: new Date('2022-8-15') }); }); </script>
3. With a set of String values
To make the datepicker range change according to the current date then you can use a defined set of string values in the options.
There are the following symbols are available –
y,m,d,+,-
Using this you can specify startDate
and endDate
values e.g. ‘+2m’,’-2m’,’+1y +10d’,’-10d’, etc
Completed Code
<div class='container' style='margin-top: 100px;'> <input type='text' class="form-control" id='datepicker' placeholder='Select Date' style='width: 300px;' ><br><br> <input type='text' class="form-control" id='datepicker2' placeholder='Select Date' style='width: 300px;' > </div> <!-- Script --> <script type="text/javascript"> $(document).ready(function(){ $('#datepicker').datepicker({ format: "yy-mm-dd", startDate: '-1y -1m', endDate: '+2m +10d' }); $('#datepicker2').datepicker({ format: "yy-mm-dd", startDate: '-1m', endDate: '+10d' }); }); </script>
4. Conclusion
Use startDate
and endDate
option to define the datepicker range where you can use fixed date values or use valid string (y,m,d,+,-) to define value.