之前已经问过这个问题,但答案并没有解决我的问题.
问题是我总是在datetime字段中收到以下错误.
问题是我总是在datetime字段中收到以下错误.
The field Created Time must be a date.
我的尝试
这是我设置日期格式的模态
[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功能日期:函数(值,元素)如下所示,但无法解决问题.
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
解决方法
试试吧
将此js代码保留在$(document).ready();的一边.仅在< script>里面< / 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 }); });
希望它会有所帮助.就我而言,它正在发挥作用.