Reputation:
This question has been asked before but the answers do not solve my problem. The problem is that I am always getting the following error with datetime field.
The field Created Time must be a date.
My Try
Here is modal where I have set date format
[Display(Name = "Created Time")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CreatedTime { get; set; }
View code
<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>
In js
$('#CreatedTime').removeAttr("data-val-date");
$('#Datetimepicker1').datetimepicker({ format: 'DD/MM/YYYY' });
Also tried to change in jquery.validate.js
funcation date: function (value, element)
as below but but unable to solve the issue.
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));
}
Visited links
The field must be a date - DatePicker validation fails in Chrome - mvc
The field date must be a date in mvc in chrome
And many more links and sites but unable to solve issue
Upvotes: 7
Views: 1489
Reputation: 21
This worked for me:
(Put that on _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));
}
};
});
credits to: http://blog.mohnady.com/2015/02/fix-aspnet-mvc-chrome-jquery-validation.html
Upvotes: 1
Reputation: 3034
Try it
Keep this js code out side of $(document).ready();
. only inside of <script>Here</script>
tag.
$(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 });
});
Hope it will be helpful. In my case it is working.
Upvotes: 4