之前已经问过这个问题,但答案并没有解决我的问题。 问题是我总是在 datetime 字段中收到以下错误。
字段创建时间必须是日期。
我的尝试
这是我设置日期格式的模态
[Display(Name = "Created Time")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CreatedTime { get; set; }
查看代码
<div class="form-group">
@Html.LabelFor(model => model.CreatedTime, "Timesheet Date")
<div class='input-group date' id='Datetimepicker1'>
@Html.TextBoxFor(model => model.CreatedTime, new { @class = "form-control" })
<span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span>
</div>
@Html.ValidationMessageFor(model => model.CreatedTime, "", new { @class = "text-danger" })
</div>
在js
$('#CreatedTime').removeAttr("data-val-date");
$('#Datetimepicker1').datetimepicker({ format: 'DD/MM/YYYY' });
还尝试更改jquery.validate.js
功能date: function (value, element)
,如下所示,但无法解决问题。
if ($.browser.webkit) {
//ES - Chrome does not use the locale when new Date objects instantiated:
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));
}
访问过的链接
The field must be a date - DatePicker validation fails in Chrome - mvc
The field date must be a date in mvc in chrome
还有更多链接和网站,但无法解决问题
答案 0 :(得分:4)
试一试
将此js代码保留在$(document).ready();
的一边。仅在<script>Here</script>
标记内。
$(function () {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#ID").datepicker({ dateFormat: 'dd/mm/yy', changeYear: true });
});
希望它会有所帮助。就我而言,它正在发挥作用。
答案 1 :(得分:1)
这对我有用:
(把它放在_Layout.cshtml上)
$(function () {
$.validator.methods.date = function (value, element) {
//Fix chrom Asp.Net MVC jQuery validation: The field "Myfield" must be a date.
var ischrom = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
if (ischrom) {
if ($.browser.webkit) {
//Chrome does not use the locale when new Date objects instantiated:
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));
}
}
else
{
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
};
});
信用到:http://blog.mohnady.com/2015/02/fix-aspnet-mvc-chrome-jquery-validation.html