ASP .NET MVC DateTime globalization. “The field Date must be a date.”

我的梦境 提交于 2019-12-24 16:58:58

问题


I have made a simple mvc app to test globalization/localization. I have made Resources.resx file and Resources.es.resx (spanish) file where I have strings that I want translated.

All strings are translated fine, but with DateTime format I am experiencing difficulties.

In the partial view I am using I use xd-soft datetimepicker for my date field like this:

razor syntax:

<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>

and the script for datetimepicker looks like this:

<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>

When i use spanish format d/m/Y its alright and when i use d.m.Y i get validation message "The field Date must be a date.".

My model looks like this:

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

回答1:


Just try this. I found this solution when my dd/MM/yyyy format is not recognized as date format.

First create a new java script file with name jquery.validate.date.js with the below code in it

$(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));
        }
    };
});

It overwrite the date validation function in jquery.validate.js

Then call the script just after jquery.validate.js like below

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

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


来源:https://stackoverflow.com/questions/31287971/asp-net-mvc-datetime-globalization-the-field-date-must-be-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!