【问题标题】:ASP .NET MVC DateTime globalization. "The field Date must be a date."ASP .NET MVC DateTime 全球化。 “字段日期必须是日期。”
【发布时间】:2015-07-08 08:58:25
【问题描述】:

我制作了一个简单的 mvc 应用程序来测试全球化/本地化。 我制作了 Resources.resx 文件和 Resources.es.resx(西班牙语)文件,其中有我想要翻译的字符串。

所有字符串都翻译得很好,但使用 DateTime 格式 我遇到了困难。

在我使用的部分视图中,我将 xd-soft datetimepicker 用于我的日期字段,如下所示:

剃刀语法:

<div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-3" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, Resources.FormatSave, new { htmlAttributes = new { @class = "form-control input-sm datetimepicker1" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

datetimepicker 的脚本如下所示:

<script type="text/javascript">

    jQuery('.datetimepicker1').datetimepicker({
        format: '@Resources.Format', //when local d.m.Y, when spanish d/m/Y
        theme: 'dark',
        lang: '@Resources.Language',
        closeOnDateSelect: true,
    });

</script>

当我使用西班牙格式 d/m/Y 时没问题,当我使用 d.m.Y 时,我收到验证消息“字段日期必须是日期。”。

我的模型如下所示:

[Display(Name = "Date", ResourceType = typeof(Resources.Resources))]
[Required(ErrorMessageResourceType = typeof(Resources.Resources),
          ErrorMessageResourceName = "DateRequired")]
[DataType(DataType.DateTime)]
public DateTime Date { get; set; }

【问题讨论】:

    标签: jquery asp.net-mvc localization date-format globalization


    【解决方案1】:

    试试这个。当我的 dd/MM/yyyy 格式未被识别为日期格式时,我找到了此解决方案。

    首先创建一个名为 jquery.validate.date.js 的新 java 脚本文件,其中包含以下代码

    $(function () {
        $.validator.methods.date = function (value, element) {
            if ($.browser.webkit) {
                var d = new Date();
                return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
            }
            else {
                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            }
        };
    });
    

    覆盖jquery.validate.js中的日期验证函数

    然后在jquery.validate.js 之后调用脚本,如下所示

    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.val.js")"/>
    
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.val.date.js")"/>
    

    【讨论】:

    • 试过了,但现在我有“0x800a138f - javascript 运行时错误无法获取未定义或空引用的属性 'webkit'”
    • 也不工作...我认为我的问题与文化有关,而不是与浏览器有关...
    • @knowkeen 你设置的文化正确吗?否则多语言将如何工作?
    • 是的,我设置它是正确的,当我编写代码 DateTime.Now 只是为了在我更改它之后测试它(当我调试时),格式正在以我想要的方式改变。但在视图上我有验证问题。我不知道为什么会这样。
    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2015-08-11
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多