39

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?

5
  • 2
    So, solved with this post -> stackoverflow.com/questions/511439/… but WHY do I need to create a custom validation method? Surely if I specify the format in the model,and specify my culture, it should use that date format?
    – mp3duck
    Aug 21, 2012 at 10:40
  • Does your server not run with the culture you require? Aug 21, 2012 at 10:44
  • @SimonWhitehead It seems that way, but this was also happening when running locally on my dev machine
    – mp3duck
    Aug 21, 2012 at 10:45
  • 4
    I've had similar issues: stackoverflow.com/questions/9821407/mvc3-en-gb-dates-in-get Because Microsoft believe no one exists outside of the US, that's why :)
    – Liam
    Aug 21, 2012 at 12:38
  • Although "no one exists outside" comment is true, it's a bit misleading I think, because not MS but majority of US developers believe no one exists outside of the US, and the same time majority of UK developers believe no one exists outside UK, and so on... May 11, 2015 at 15:36

5 Answers 5

103

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;
    });
});
3
  • 3
    There is an international date validation method that can be used instead in the additional-methods.js library.
    – Rowan
    Jun 18, 2013 at 9:05
  • In my case I've replaced the parseDate() call because I wanted to use date and time (and it seems the datepicker doesn't support this), so I've used this: ` var re = /\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d/; var ok; try { ok = value.match(re) != null; } `
    – lutecki
    Oct 27, 2015 at 17:30
  • Just to clarify, @lutecki's regex expression validates yyyy-mm-dd hh:mm
    – bluedot
    Jan 15, 2018 at 15:47
12

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

1
  • It's a great thing you put it on a blog and explained the whole procedure step by step, thanks. Apr 29, 2014 at 14:57
4

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

3

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.

2
  • Hi Aim, looks like a nice simple solution. Where do you insert this?
    – mattpm
    Jan 19, 2017 at 22:51
  • 1
    @mattpm you will insert it in the JavaScript code for the view that have a date field
    – iAM
    Jan 20, 2017 at 6:10
1

Try change this direct in jquery.validate.js. Work with $.datpicker

date: function (value, element) {
    var s = value;

    var ind2 = 3;
    var ind3 = 6;
    var ind4 = 4;

    if (s.substr(6, 1) != "2") {
        ind2 = ind2 + 1;
        ind3 = ind3 + 1;
        ind4 = ind4 + 1;
    }

    var ndan = s.substr(0, 2);
    var nmje = s.substr(ind2, 2);
    var ngod = s.substr(ind3, ind4);

    var ns = ngod + "," + nmje + "," + ndan;

    return this.optional(element) || !/Invalid|NaN/.test(new Date(ns));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.