ASP MVC 5日期格式验证问题 [英] ASP MVC 5 Date Format Validation Issue

查看:74
本文介绍了ASP MVC 5日期格式验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP MVC 5 Web应用程序中,我需要以特定格式显示日期.页面加载时,文本格式正确.但是,如果您编辑值或只是尝试发布,则显示验证错误:

In my ASP MVC 5 web application, I need to display a date in a specific format. When the page loads, the text is formatted correctly. But if you edit the value or simply try to post, the validation error is shown:

该字段的定义如下:

        @*Creation*@
    <div class="form-group">
        @Html.LabelFor(model => model.Creation, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Creation, "{0:dd/MM/yyyy}", new { @class = "form-control"})
            @Html.ValidationMessageFor(m => m.Creation)
        </div>
    </div>

viewmodel属性定义为:

The viewmodel property is defined as:

        [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Creation", ResourceType = typeof(Resources.Resources))]
    public DateTime Creation { get; set; }

该屏幕截图是使用Firefox浏览器创建的.如果在Edge上执行相同的操作,则验证通过,但是此属性在post方法上的出价无效(默认日期值).

The screenshot was created using Firefox browser. If I do the same on Edge, the validation passes, but the biding of this property on the post method is invalid (a default date value).

如何解决此问题?

推荐答案

这里的问题是,在后台验证实际上是由jQuery执行的.因此,关键是要告诉 jQuery验证程序,您将使用 dd/MM/yyyy 格式.

The problem here is that, behind the scenes, the validation is actually being performed by jQuery. So the key is to tell the jQuery validator that you will be using the dd/MM/yyyy format.

有两种方法可以做到这一点.最简单的方法是使用simpe调整仅覆盖验证器功能(用于日期):

There are a couple ways of doing this. The simplest way is to just override the validator function (for dates) with a simpe tweak:

jQuery(function ($) {
    $.validator.addMethod('date',
    function (value, element) {
      $.culture = Globalize.culture("en-AU");
      var date = Globalize.parseDate(value, "dd/MM/yyyy", "en-AU");
      return this.optional(element) || 
        !/Invalid|NaN/.test(new Date(date).toString());
    });
});

另一种选择是对jQuery使用全球化库.您可以在此处使用一个全球化库.

An alternative would be to use a globalization library for jQuery. There is a globalization library that you can use here.

拥有该库后,请包括以下文件:

When you have the library, include these files:

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

然后覆盖验证器功能:

<script type="text/javascript">
    $(function () {
        $.validator.methods.date = function (value, element) {
            Globalize.culture("en-AU"); // the UK format
            return this.optional(element) || Globalize.parseDate(value) !== null;
        }
    });
</script>

这篇关于ASP MVC 5日期格式验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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