MVC 4 如何通过客户端验证来验证非美国日期? [英] MVC 4 how to validate a non-US date with client validation?

查看:25
本文介绍了MVC 4 如何通过客户端验证来验证非美国日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了在客户端验证日期时间字段时遇到问题的情况.当我尝试提交时,它一直告诉我日期无效(27/7/2013).但如果我将日期转换为美国格式,它就可以工作(07/27/2013).

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).

我的视图模型如下,

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

索引.html

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

我已经更新了我的 web.config

I have updated my web.config

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

我错过了什么?

谢谢

推荐答案

其他人帮我整理了这个,这完全与客户端 Jquery 验证有关.再次感谢 asymptoticFault .. 你摇滚..MVC 4 日期文化问题?

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...

问题是 jQuery 验证在解析日期时没有考虑文化.如果您关闭客户端验证,则可以在了解文化的服务器上很好地解析日期.

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.

修复方法是覆盖日期的 jQuery 验证并包含一个额外的 jQuery 全球化插件.您可以在此处找到全球化插件.您还可以使用 Nuget 包管理器轻松下载该插件.我刚刚打开包管理器,选择左侧的 Online 选项卡并在搜索中输入globalize",这是第一个结果.安装后,我包含了这两个文件:

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

您可以使用脚本标签直接包含它们,也可以将它们放在一个包中,也许与其他 jQuery 验证文件一起使用.

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

一旦你有了这些,你将需要添加以下脚本来覆盖日期的 jQuery 验证:

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>

这篇关于MVC 4 如何通过客户端验证来验证非美国日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆