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
Some others have asked the question about setting the max date to the current date. The suggested answers involve using JavaScript. But my solution was to use the server side language to generate the max parameter for the input. I know the OP didn't ask about a server-side approach. But this solution works well for me using C# Razor as my server language.
On the server I write:
@Html.TextBox("CurrentDate",
Model.CurrentDate.ToString("yyyy-MM-dd"),
new {
@class = "form-control",
@type = "date",
max = DateTime.Now.ToString("yyyy-MM-dd")
})
And then MVC outputs this Html:
<input class="form-control" id="CurrentDate" name="CurrentDate"
type="date" max="2016-11-10" value="2016-11-10">
With other server languages the approach would be to similarly generate the max parameter using the Server's date, which may or may not work if your requirement is to use the Client's date. For my situation the Server's date is what is needed because that's where the data is stored.
You can use min and max attributes of HTML5 input date
HTML5 code
<input type="date" name="bday" min="2014-05-11" max="2014-05-20">
EDIT
You need to use jQuery to achieve it
jQuery code
$(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;
$('#txtDate').attr('max', maxDate);
});
Explanation max attribute of HTML5 input date takes month and day in double digit format.
Ex: 5 (Month) is not valid whereas 05 (Month) is valid Ex: 1 (Day) is not valid whereas 01 (Day) is valid
So I have added below code
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
Check my updated fiddle
Refer fiddle demo