The field date must be a date in mvc in chrome [duplicate]
I'm doing a simple MVC4 Internet application, which allows to add some items to the categories.
Here is what i've done so far.
I've a datepicker in mvc view. The script for the datepicker is like this.
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('#dtItemDueDate').datepicker({
dateFormat: 'dd/mm/yy',
minDate: 0
});
});
</script>
My model property :
[DisplayName("Item DueDate")]
[Required]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
[DataType(DataType.DateTime)]
public DateTime? dtItemDueDate { get; set; }
public char charCompleted { get; set; }
and in my view i've done this:
@Html.TextBoxFor(m => m.dtItemDueDate)
@Html.ValidationMessageFor(m => m.dtItemDueDate)
The error is like this:
The field Item DueDate must be a date.
The strange this is that it does work in IE and mozilla, but doesnot work in Chrome.
I found many posts on SO, but none of them help
Any ideas/suggestions ?
Without changing jquery.validate.js, you can use the code snip below in $(document).ready()
:
jQuery.validator.methods.date = function (value, element) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (isChrome) {
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));
}
};
Editor note: This answer is no longer valid, as of jQuery 1.9 (2013) the $.browser
method has been removed
According to this post it's a known quirk with Webkit-based browsers.
One solution is to modify jquery.validate.js
by finding the function date: function (value, element)
and put this code in it:
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));
}