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 ?

Here's Maxim Gershkovich's solution spelled out a little more:

<!-- language: lang-js -->
jQuery.validator.methods.date = function (value, element) {
    if (value) {
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        } catch (ex) {
            return false;
        }
    }
    return true;
};

Notes:

  • This depends on the jQuery datepicker method that comes with jQuery UI

  • This is actually more robust that the native date validation that comes with jQueryValidate.

    According to the docs on date validation:

    Returns true if the value is a valid date. Uses JavaScript's built-in Date to test if the date is valid, and therefore does no sanity checks. Only the format must be valid, not the actual date, eg 30/30/2008 is a valid date.

    Whereas parseDate will check that the date is valid and actually exists.