ASP MVC 5 Client Validation for Range of Datetimes

后端 未结 5 1654
旧巷少年郎
旧巷少年郎 2020-12-06 12:44

I want to check an Datetime field in a form. The field is valid between 01/10/2008 and 01/12/2008. Here is how I defined the viewmodel property:

    [Require         


        
5条回答
  •  被撕碎了的回忆
    2020-12-06 13:14

    You must specify dates in a certain format on the attribute and you also much provide the value in that format as well. The date input doesn't like MM/dd/yyyy, even though that's the format it displays in! Pretty retarded IMHO.

    You need to add min and max like so:

    Resulting Html

    
    

    Model

    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    public DateTime DOB { get; set; }
    

    View

    @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control", min = "1900-01-01", max = "2015-01-01" } })
    

    Then you will get min or max errors in the UI:

提交回复
热议问题