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" />
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" />
+6
source to share
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 to share
$(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 to share
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 to share