[英]Validation failing because of date format
我有一個帶有出生日期字段的MVC6編輯視圖,如下所示:
<div class="form-group">
@Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })*@
@Html.EditorFor(m => m.DateOfBirth,new { htmlAttributes = new { @readonly = "readonly" } })
@Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
</div>
</div>
因此,當我單擊“保存”時,錯誤提示:值'07 / 17/1981'對ApplicationDate無效。 如何確保日期以英國格式顯示,意味着驗證成功。
我將以下答案添加到Bubdle.Config中:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/globalize.js",
"~/Scripts/jquery.validate.globalize.js"));
像這樣更新模型:
// Add this attribute
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
我假設您的錯誤是客戶端? 即不打擾的驗證? 已發布的解決方案的另一種解決方案是使用全球化。
有一個可用的Nuget包“ jQuery.Validation.Globalize。您可以安裝此包,並在jqueryval捆綁包中包含全球化的Javascript文件。
您可以通過導航到App_Start
目錄並編輯BundleConfig.cs
文件來實現。 您將看到應該已經有用於bundles/jqueryval
的ScriptBundle
您可以將globalize.js
和jquery.val.globalize.js
文件的路徑添加到其中,或者創建單獨的ScriptBundle
以在View中引用。
注意:僅當按如下所示將CultureInfo
添加到Global.asax文件時,此方法才有效。
您還需要將以下內容添加到Global.asax文件中。
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
在導演Views/Shared/EditorTemplates
我添加了一個UKDate
視圖。
我的特定視圖的代碼是:
@model DateTime?
@{
if (Model.HasValue)
{
var classname = ViewData["class"];
var id = ViewData["id"];
<input type="text"
name="@ViewData.TemplateInfo.HtmlFieldPrefix" //this needed to map the input to the property in your model, by the default model binder.
value="@Model.Value.ToString("dd/MM/yyyy")"
class="@classname"
id="@id"
/>
}
}
然后使用它執行以下操作:
@Html.EditorFor(x => x.YourDateFieldDate, "UKDate", new { @class = "any css classes required here", id = "Id here" })
由於現在沒有data-val-date
屬性,因此無法運行驗證。 因此,如果您不關心任何客戶端日期驗證,就可以解決此問題。
看一下此頁面上的示例,檢查它是否滿足您的要求。
https://johnnyreilly.github.io/jQuery.Validation.Unobtrusive.Native/AdvancedDemo/Globalize.html
我看到您問為什么要包含jquery,答案是因為Microsoft驗證要歸功於jquery,因此他們共同努力實現了這一目標。
如果您的頁面是英語(英語),則可以使用默認驗證,但如果您的文化與我的不同,則至少需要包括該頁面中提到的內容(基本上是jquery,globalize和validation)。
全球化將覆蓋驗證以在您期望的文化中工作。
試試看,讓我知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.