Restrict future dates in HTML5 date input

后端 未结 8 1438
误落风尘
误落风尘 2020-11-29 06:50

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

相关标签:
8条回答
  • 2020-11-29 07:00

    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

    0 讨论(0)
  • 2020-11-29 07:00

    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.

    0 讨论(0)
  • 2020-11-29 07:03
        <input type="date" value="<?php echo date("Y-m-d"); ?>" max="<?php echo date("Y-m-d"); ?>">
    

    This worked for me.

    0 讨论(0)
  • 2020-11-29 07:04

    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

    0 讨论(0)
  • 2020-11-29 07:08

    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);
    
    0 讨论(0)
  • 2020-11-29 07:09

    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();
                        }
                    });   
    
    0 讨论(0)
提交回复
热议问题