How to limit past dates in html5 Date input format

I am trying to limit past dates in input type="date"

. I can limit future dates, but I have no idea about limiting past dates.

$(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 minDate= year + '-' + month + '-' + day;
    
    $('#txtDate').attr('min', minDate);
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="txtDate" />
      

Run codeHide result


Any suggestion?

+6


source to share


5 answers


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" />
      

Run codeHide result


+6


source


Hope the below code helps you. This 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

+5


source


In HTML:

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

      

Using the newer version of Jquery:

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); }

      

+2


source


  $(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


source


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 two-digit format for the day and month. https://www.php.net/manual/en/function.date.php

0


source







All Articles