MVC 4 how to validate a non-US date with client validation?

后端 未结 4 1708
借酒劲吻你
借酒劲吻你 2020-12-03 08:07

I have a situation where I am having trouble with the client side validation of a datetime field. When I try to submit it keeps telling me the date is invalid (27/7/2013).

4条回答
  •  渐次进展
    2020-12-03 09:03

    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. 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();
        }
    });
    

提交回复
热议问题