how to fix 'The field must be a date' on a datetime property in mvc

前端 未结 13 1125
逝去的感伤
逝去的感伤 2020-12-29 06:59

I need to capture date and time both for my model property. In my model class I have the following

[Required]
[DataType(DataType.DateTime)]
public DateTime?          


        
相关标签:
13条回答
  • 2020-12-29 07:32

    Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. It is not caused by datepicker nor browsers. Unfortunately you have to solve it manually.

    My finally working solution:

    You have to include before:

    @Scripts.Render("~/Scripts/jquery-3.1.1.js")
    @Scripts.Render("~/Scripts/jquery.validate.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
    @Scripts.Render("~/Scripts/moment.js")
    

    You can install moment.js using:

    Install-Package Moment.js
    

    And then you can finally add fix for date format parser:

    $(function () {
        $.validator.methods.date = function (value, element) {
            return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
        }
    });
    
    0 讨论(0)
提交回复
热议问题