Restrict future dates in HTML5 date input

后端 未结 8 1444
误落风尘
误落风尘 2020-11-29 06:50

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

8条回答
  •  北海茫月
    2020-11-29 07:17

    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:

    
    

    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.

提交回复
热议问题