Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict past dates in html5 input type Date

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.

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

Any suggestion?

like image 986
user7397787 Avatar asked Apr 07 '17 09:04

user7397787


People also ask

How do I limit the date selection in HTML?

You can add a min or max attribute to the input type=date . The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.

Which html5 attributes can be used with html5 date input type to limit date selection?

The max attribute specifies the maximum value (date) for a date field. Tip: Use the max attribute together with the min attribute to create a range of legal values. Tip: To set or return the value of the min attribute, use the min property.

How do I set the calendar to not allow dates before today's date in HTML?

toISOString(). split('T')[0]; document. getElementsByName("setTodaysDate")[0]. setAttribute('min', today);

How do I turn off previous dates in calendar?

the previous dates we need to set the minDate property of the date picker. if we set minDate:0 then it will disable all the previous dates. and we set input attribute min:current_date then it will disable all the previous dates.


1 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;

    // or instead:
    // var maxDate = dtToday.toISOString().substr(0, 10);

    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" />
like image 149
Dhiraj Avatar answered Oct 13 '22 06:10

Dhiraj