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