Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC 4 how to validate a non-US date with client validation?

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). But if I turn the date into US format it works (07/27/2013).

My view model is as follows,

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

Index.html

 @Html.TextBoxFor(m => m.AuditDate)

I have updated my web.config

<globalization culture="en-AU" uiCulture="en-AU" />

What have I missed out on?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Someone else sorted this for me, it was all to do with the client side Jquery validation. Thanks again asymptoticFault.. you rock.. MVC 4 date culture issue?

Here is the info from that link that I used...

The problem is the jQuery validation not accounting for the culture when parsing a date. If you turn off the client side validation the date is parsed just fine on the server that is aware of the culture.

The fix is to override the jQuery validation for date and include an additional jQuery globalization plugin. You can find the globalize plugin here. You can also easily download the plugin using the Nuget Package Manager as well. I just opened the package manager, selected the Online tab on the left and typed "globalize" into the search and it was the first result. Once you have it installed I included these two files:

globalize.js 
globalize.culture.en-AU.js

You can either include them directly using a script tag or place them in a bundle, perhaps with the other jQuery validation files.

Once you have those you will need to add the following script to override the jQuery validation for date:

<script type="text/javascript">
    $(function () {
        $.validator.methods.date = function (value, element) {
            Globalize.culture("en-AU");
            // you can alternatively pass the culture to parseDate instead of
            // setting the culture above, like so:
            // parseDate(value, null, "en-AU")
            return this.optional(element) || Globalize.parseDate(value) !== null;
        }
    });
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...