MVC DateTime validation - UK Date format

I have a simple view with two date fields with ValidationMessageFor controls added for the unobtrusive JavaScript validation.

My issue is I keep getting told my date is invalid, when it is in correct format (dd/MM/yyyy)

I have added <globalization culture="en-GB" uiCulture="en-GB"/> to my web.config, and also included [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] on each DateTime property, yet it still won't accept UK format dates.

Is there anything obvious I am missing here?


Actually you just need to overload unobtrusive JavaScript validation method for date

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

Bohdan's example worked a treat! I've +1 your answer mate.

For completeness I've written a blog post on how to integrate all the parts (Model, View, custom EditorTemplate, jQuery includes and adding Bohdan's solution).

You can read it here: http://www.kestrelblackmore.com/blog/jquery-datepicker-mvc4


I know it's old but using this I added to the input an attribute with the current date format (which I fetched from the ASP MVC code with CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToLower()).

Then I rewrote the validation javascript to use the format found in the attribute.

        var format = "mm/dd/yyyy";
        if (element.attributes["data-format"]) {
            format = element.attributes["data-format"].value;
        }

I also read the same attribute for the jquery ui datepicker. It might not be that usefull but it can keep the format consistent with the culture at least. Though it could help someone


I have taken a different approach to solve this compared to other answers. Use jQuery to add a new date function which will force the date to use the current local culture set in the application.

$.validator.addMethod('date', function (value, element) {
                var d = new Date();
                return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
            });

That is if it fails on jQuery validation. I credit this answer to Elton Stoneman post which can be read here

Hope this will help someone else.