簡體   English   中英

盡管有 en-GB 文化,.NET MVC UK 日期格式仍無法驗證

[英].NET MVC UK date format won't validate despite culture en-GB

我在 MVC 中有一系列 Web 表單。 最近對網站進行了一些更新后,DateTime 字段驗證假設日期為美國格式,因此超過 12 天的天數未通過驗證,盡管我已將編輯日期格式、驗證代碼和文化指定為 en- GB。 嘗試了各種瀏覽器,所有語言都設置為英語(英國),在 Firefox、Chrome 和 Edge 中驗證失敗,僅適用於 IE。 嘗試了在這里找到的各種其他建議,包括 ModelBinding,但似乎沒有任何效果。

在課堂里:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

在 web.config 中:

<globalization culture="en-GB" uiCulture="en-GB" requestEncoding="utf-8" responseEncoding="utf-8" enableClientBasedCulture="false" />

在 global.asax 中:

CultureInfo newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
newCulture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

在 jquery.validate.js 中:

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

還有其他建議嗎?

我讓它與 MVC 5 一起正常工作。 需要進行兩項更改:

  1. 添加模型綁定器,因為默認綁定器不考慮 CurrentUICulture。 我這樣做是為了測試它而刪除了客戶端驗證。 默認情況下它不使用的原因是您可能會在 URL 中使用日期,盡管我想如果我這樣做了,我會想沿 yyyy-mm-dd 行格式化 URL。
  2. 更改客戶端驗證以考慮英國日期。 我不確定您的 jquery.validate.js 代碼是否有效。 我也遇到了一些麻煩,所以最后我安裝了 nuget 包 jQuery.Validation.AdditionalMethods 並制作了使用它的代碼。

我自己在http://www.ablogaboutcoding.com/2017/08/12/mvc-uk-date-issues/ 上的博客文章進一步解釋了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM