How do I restrict past dates in html5 input type Date

前端 未结 7 2119
天命终不由人
天命终不由人 2020-12-10 16:40

I am trying to restrict past dates in input type=\"date\".I can able to restrict future dates,But I don\'t have idea about restricting past dates.

相关标签:
7条回答
  • 2020-12-10 17:20
      $(function() {
              $(document).ready(function () {
                var todaysDate = new Date();
                var year = todaysDate.getFullYear();
                var month = ("0" + (todaysDate.getMonth() + 1)).slice(-2);
                var day = ("0" + todaysDate.getDate()).slice(-2);
                var maxDate = (year +"-"+ month +"-"+ day);
                $('.class_of_input_field').attr('min',maxDate);
              });
            });``
    
    0 讨论(0)
  • 2020-12-10 17:22

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

    <input type="date" id="txtDate" min="<?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-12-10 17:23

    You can try this

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

    $(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;
        alert(maxDate);
        $('#txtDate').attr('min', maxDate);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="date" id="txtDate" />

    0 讨论(0)
  • 2020-12-10 17:27

    Programmatically you can do something like this to disable past dates from being selectable:

    <input type='date' min={new Date().toISOString().split('T')[0]} />
    
    0 讨论(0)
  • 2020-12-10 17:34

    In HTML:

    <input type="date" id="ExpiryDate" class="form-control" min="9/10/2018"/>
    

    Using Jquery new version:

    function SetMinDate() {
        var now = new Date();
    
        var day = ("0" + now.getDate()).slice(-2);
        var month = ("0" + (now.getMonth() + 1)).slice(-2);
    
        var today = now.getFullYear() + "-" + (month) + "-" + (day);
    
        $('#ExpiryDate').val(today);
        $('#ExpiryDate').attr('min', today); }
    
    0 讨论(0)
  • 2020-12-10 17:35

    Hope below code will help you. It is normal HTML5 code:

    /*Enter a date before 1980-01-01:*/
    <input type="date" name="bday" max="1979-12-31">
    
    /*Enter a date after 2000-01-01:*/
    <input type="date" name="bday" min="2000-01-02">
    

    see working link

    0 讨论(0)
提交回复
热议问题