41

I want to restrict a user to only being able to add future dates in a HTML date input.

Instead of jQuery UI date picker I want to add HTML5 calender. Can anyone tell me how can I restrict the input to future dates?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Erandi
  • 719
  • 3
  • 7
  • 16
  • 1
    Possible duplicate of [Disable certain dates from html5 datepicker](http://stackoverflow.com/questions/17182544/disable-certain-dates-from-html5-datepicker) – Stubborn Dec 20 '16 at 19:23

12 Answers12

90

You can use min and max attributes of HTML5 input date

HTML5 code

<input type="date" name="bday" min="2014-05-11" max="2014-05-20">

EDIT

You need to use jQuery to achieve it

jQuery code

$(function(){
    var dtToday = new Date();

    var month = dtToday.getMonth() + 1;
    var day = dtToday.getDate();
    var year = dtToday.getFullYear();

    if(month < 10)
        month = '0' + month.toString();
    if(day < 10)
        day = '0' + day.toString();

    var maxDate = year + '-' + month + '-' + day;    
    $('#txtDate').attr('max', maxDate);
});

Explanation max attribute of HTML5 input date takes month and day in double digit format.

Ex: 5 (Month) is not valid whereas 05 (Month) is valid Ex: 1 (Day) is not valid whereas 01 (Day) is valid

So I have added below code

if(month < 10)
   month = '0' + month.toString();
if(day < 10)
   day = '0' + day.toString();

Check my updated fiddle

Refer fiddle demo

Chirag Vidani
  • 2,519
  • 18
  • 26
  • @ Chirag but if we use max date like this we have to change it every time neah instead can't we use something like new Date () ( which we use to restrict future dates in JQuery ) to this max attribute – Erandi May 15 '14 at 07:16
  • @Erandi Not able to get you – Chirag Vidani May 15 '14 at 07:17
  • @ Chirag ..friend here if you add max date as 2014-05 -20 then suppose if user fill a form on 2014-06-01 then at that time we can't use max date as this date neah so it's better if there is a option that it restrict user to enter future date according to the current date in his/her pc – Erandi May 15 '14 at 07:23
  • @Erandi Check edited answer, now you can provide dynamic date runtime using jquery attr() method. I think this update should solve your query – Chirag Vidani May 15 '14 at 07:38
  • @ Chirag .Thanks a lot friend .. can you please help me to understand this code because I'm not good in JQuery please tell me why you use this code segment ? "if(month < 10) month = '0' + month.toString(); " – Erandi May 15 '14 at 07:44
  • @Erandi The condition is not related jQuery, its just value manipulation. Please refer my updated answer. – Chirag Vidani May 15 '14 at 07:49
  • 4
    This example doesn't appear to "need to use jQuery to achieve it". The majority of the example doesn't even use jQuery. What was the reason for saying that jQuery was needed? – razorsyntax Nov 30 '17 at 16:37
  • Sadly, doesn't work on iOS. – Zoltán Matók May 03 '22 at 11:29
36

To build on @Chirag Vidani's answer, the date can be generated with fewer lines like this:

var now = new Date(),
    // minimum date the user can choose, in this case now and in the future
    minDate = now.toISOString().substring(0,10);

$('#my-date-input').prop('min', minDate);
Juank
  • 6,096
  • 1
  • 28
  • 28
  • 1
    This is the cleanest way to get the date to HTML5 format. – dlsso Oct 19 '15 at 15:37
  • 1
    This is cleanest way but wrongly set to `min` instead of `max` – Morteza Tourani Jun 23 '16 at 01:28
  • 1
    Note that the date produced by toISOString is the UTC date, which may be different to the local date by 1 day depending on when the code is run and the timezone offset of the host. – RobG Oct 02 '19 at 00:31
  • @MortezaTourani my understanding is that the OP needed a date input in which only dates in the future can be selected. Any date from now and to the future is valid, dates from now and to the past should not be available. Hence the "min" property is used, as now is the "min(imum)" date the user can choose and there is no max. Setting it to "max" will only allow selecting dates in the past. Just clarifying for others in case I misunderstood the original question. – Juank Jan 19 '20 at 21:25
  • 1
    @Juank What you've done and explained is exactly what I meant. However someone edited your answer and replaced `min` with `max` so, I think it's better to revert the edit. – Morteza Tourani Jan 20 '20 at 16:48
11

Here is a PHP solution that gets today's date and sets it as the maximum.

<input type="date" name="bday" max="<?php echo date("Y-m-d"); ?>">

This will put it in the correct double-digit format for the day and month. https://www.php.net/manual/en/function.date.php

Painguin
  • 1,027
  • 14
  • 26
5

Some others have asked the question about setting the max date to the current date. The suggested answers involve using JavaScript. But my solution was to use the server side language to generate the max parameter for the input. I know the OP didn't ask about a server-side approach. But this solution works well for me using C# Razor as my server language.

On the server I write:

@Html.TextBox("CurrentDate",
    Model.CurrentDate.ToString("yyyy-MM-dd"),
    new {
        @class = "form-control",
        @type = "date",
        max = DateTime.Now.ToString("yyyy-MM-dd")
    })

And then MVC outputs this Html:

<input class="form-control" id="CurrentDate" name="CurrentDate"
    type="date" max="2016-11-10" value="2016-11-10">

With other server languages the approach would be to similarly generate the max parameter using the Server's date, which may or may not work if your requirement is to use the Client's date. For my situation the Server's date is what is needed because that's where the data is stored.

FirstVertex
  • 3,657
  • 34
  • 33
4

Use the max attribute which is the expected upper bound for the element's value.

<input type="date" max="2014-05-15"/>

Reference: http://www.w3.org/TR/html-markup/input.date.html

James Hibbard
  • 16,490
  • 14
  • 62
  • 74
2

I have updated the Working fiddle

http://jsfiddle.net/9WVY8/16/

HTML & js:

     var dateControler = {
                currentDate : null
            }

             $(document).on( "change", "#txtDate",function( event, ui ) {
                    var now = new Date();
                    var selectedDate = new Date($(this).val());

                    if(selectedDate > now) {
                        $(this).val(dateControler.currentDate)
                    } else {
                        dateControler.currentDate = $(this).val();
                    }
                });   
Vinoth
  • 21
  • 1
2
    <input type="date" value="<?php echo date("Y-m-d"); ?>" max="<?php echo date("Y-m-d"); ?>">

This worked for me.

anuj rajak
  • 49
  • 6
1

Old Question But a solution, may help someone using JQuery:

    $(document).ready(function () {
        var today = new Date();
        var day=today.getDate()>9?today.getDate():"0"+today.getDate(); // format should be "DD" not "D" e.g 09
        var month=(today.getMonth()+1)>9?(today.getMonth()+1):"0"+(today.getMonth()+1);
        var year=today.getFullYear();

        $("#dpFromDate").attr('max', year + "-" + month + "-" + day);
});

The date format should be YYYY-MM-DD.

ccaring
  • 33
  • 3
0

you can get that only using JS and HTML:

first let's get the actual date

let n =  new Date();
let y = n.getFullYear();
let m = n.getMonth() + 1;
let d = n.getDate();

and lets do the minDate and Max date strings, and evaluate if we'll need put a 0 in the month/day to keep the required format:

if(m < 10)
   m = '0' + m.toString();
else if(d < 10)
   d = '0' + d.toString();

let minDate = y + '-' + m + '-' + d
let maxDate = y + '-' + "0"+(parseFloat(0+m) + 1) + '-' + d

after, lets set it in the HTML:

<input name="Fecha_end" type="date" id="#Fecha_end">

let Fecha_end_input = document.getElementById("#Fecha_end")

Fecha_end_input.setAttribute("min",minDate)
Fecha_end_input.setAttribute("max",maxDate)

Total:

HTML:

<input name="Fecha_end" type="date" id="#Fecha_end">

JS:

let Fecha_end_input = document.getElementById("#Fecha_end")

let n =  new Date();
let y = n.getFullYear();
let m = n.getMonth() + 1;
let d = n.getDate();
if(m < 10)
   m = '0' + m.toString();
else if(d < 10)
   d = '0' + d.toString();

let minDate = y + '-' + m + '-' + d
let maxDate = y + '-' + "0"+(parseFloat(0+m) + 1) + '-' + d

Fecha_end_input.setAttribute("min",minDate)
Fecha_end_input.setAttribute("max",maxDate)
0
<script>
   var today = new Date().toISOString().slice(0, 16);                 
   document.getElementsByName("time_start")[0].max = today;  
</script>  

and input id="time_start"

Dylan
  • 2,161
  • 2
  • 27
  • 51
ramal
  • 1
  • 1
0

Html with Vue

<input type="month" :max="getTodaysMonth()">

Vue:

getTodaysMonth() {
 var today = new Date();
 var month = today.getMonth() + 1;
 var year = today.getFullYear();
 if (month < 10) {
  month = "0" + month;
 }
 return year + "-" + month;
}
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34135161) – Andrew Apr 04 '23 at 22:07
0

You can use Javascript to achieve the desired effect. Here is an example that will guarantee that your form date field only accepts dates between today and the next year. You can adjust the code based on your needs.

<input id="dateInput" type="date" name="date">
   <script>
      const dateInput = document.getElementById('dateInput');

      const today = new Date();
      const oneYearFromToday = new Date();
      oneYearFromToday.setFullYear(today.getFullYear() + 1);

      dateInput.min = formatDate(today);
      dateInput.max = formatDate(oneYearFromToday);

      function formatDate(date) {
         const year = date.getFullYear();
         const month = String(date.getMonth() + 1).padStart(2, '0');
         const day = String(date.getDate()).padStart(2, '0');
         return `${year}-${month}-${day}`;
      }
   </script>

Load the <script> in the body section of your document.