MVC DateTime validation - UK Date format
Asked Answered
S

5

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?

Spirketing answered 21/8, 2012 at 10:31 Comment(5)
So, solved with this post -> #511939 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?Spirketing
Does your server not run with the culture you require?Habakkuk
@SimonWhitehead It seems that way, but this was also happening when running locally on my dev machineSpirketing
I've had similar issues: https://mcmap.net/q/409004/-binding-en-gb-dates-in-a-http-get Because Microsoft believe no one exists outside of the US, that's why :)Brakpan
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...Brython
D
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;
    });
});
Db answered 29/12, 2012 at 12:6 Comment(3)
There is an international date validation method that can be used instead in the additional-methods.js library.Koan
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; } `Tm
Just to clarify, @lutecki's regex expression validates yyyy-mm-dd hh:mmSustenance
O
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

Obstacle answered 31/7, 2013 at 1:59 Comment(1)
It's a great thing you put it on a blog and explained the whole procedure step by step, thanks.Henn
G
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

Ghiselin answered 18/2, 2015 at 16:43 Comment(0)
H
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.

Holeproof answered 26/2, 2015 at 23:1 Comment(2)
Hi Aim, looks like a nice simple solution. Where do you insert this?Foresee
@Foresee you will insert it in the JavaScript code for the view that have a date fieldHoleproof
E
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));
Engedus answered 6/6, 2017 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.