MVC 5没有使用自定义DateTime注释正确验证Model的字段

问题描述 投票:0回答:1

在我的ASP.NET MVC 5项目中,我添加了一个DataAnnotation来格式化模型的DateTime字段,如“dd / mm / yyyy”,但是当这个字段在编辑视图中由@Html.Editor呈现时,这仍然被验证为日期比如“mm / dd / yyyy”(例如,如果我插入“13/12/2019”之类的日期,我收到错误,因为第13天被验证为一个月)。

这是从数据库生成的实体模型:

namespace MyProject
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class Supplier
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Supplier()
        {
            this.Brands = new HashSet<Brand>();
        }

        public long Id { get; set; }
        public string Name { get; set; }
        public string Agent { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }

        public Nullable<System.DateTime> NextOrderDate { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Brand> Brands { get; set; }
    }
}

我使用解决方法explained here添加DataAnnotations,以便在从数据库重新生成实体时不会消除它们,所以我还添加了这个元数据类:

namespace MyProject
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    [MetadataType(typeof(SupplierMetadata))]
    public partial class Supplier
    {
        // Note this class has nothing in it.  It's just here to add the class-level attribute.
    }

    public class SupplierMetadata
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string Agent { get; set; }

        [Required]
        public string Address { get; set; }

        [Required]
        public string Phone { get; set; }

        [Required]
        public string Email { get; set; }

        [Display(Name = "Next Order")]
        [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")]
        public Nullable<System.DateTime> NextOrderDate { get; set; }

    }

这就是我的领域呈现方式:

<div class="form-group">
    @Html.LabelFor(model => model.NextOrderDate, htmlAttributes: new { @class = "col-form-label col-lg-2" })
    <div class="col-lg-10">
        @Html.EditorFor(model => model.NextOrderDate, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.NextOrderDate, "", new { @class = "text-danger" })
    </div>
</div>

我还将此代码添加到Global.asax.cs但没有任何更改:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MyProject
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            CultureInfo newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            newCulture.DateTimeFormat.ShortDatePattern = "dd/mm/yyyy";
            newCulture.DateTimeFormat.DateSeparator = "/";
            Thread.CurrentThread.CurrentCulture = newCulture;

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
asp.net asp.net-mvc-5 data-annotations datetime-format date-formatting
1个回答
1
投票

我解决了这个问题,因为jQuery验证在解析日期时没有考虑文化。如果关闭客户端验证,则在知道文化的服务器上解析日期就好了。修复是覆盖日期的jQuery验证,并包含一个额外的jQuery全球化插件。

我最终的解决方案是

  • 使用以下命令安装moment.js: Install-Package Moment.js

然后在视图中添加日期格式解析器的修复:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/moment.js")

    <script>


        $(function () {
            $.validator.methods.date = function (value, element) {
                return this.optional(element) || moment(value, "DD/MM/YYYY", true).isValid();
            }
        });
    </script>
}
© www.soinside.com 2019 - 2024. All rights reserved.