The field date must be a date in mvc in chrome

Karthik Chintala picture Karthik Chintala · Mar 29, 2013 · Viewed 41.6k times · Source

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 ?

Answer

Mahesh picture Mahesh · Dec 20, 2013

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));
    }
};