1

I upgraded a mvc 3 web app to mvc 4, following the instructions for manual uppgrade. Everything went OK, and the app is running in IE9. I have forms with fields of several data types with both client side and server side validation and all are processed correctly when the form is submitted.

But when i use other browser - tested with Firefox 8, Chrome 15 and Safari 5.1.1 - It fails when validating date fields. I´'m using the 'pt-PT' culture with dates on the format dd-MM-yyyy, and as I said, in IE9 they pass validation, but on the other browsers it says the field is not a valid date.

TIA

Joaquim

Joaquim Franco
  • 248
  • 4
  • 9

1 Answers1

8

I found that the problem was in JQuery validation. It calls the javascript Date constructor to check if the date is valid:

    // http://docs.jquery.com/Plugins/Validation/Methods/date
    date: function(value, element) {
        return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
    },

Since javascript Date constructor is expecting a date in the form yyyy-MM-dd it returned Invalid for dates in portuguese format dd-MM-yyy.

The exception is IE that does not return Invalid but a date diferent from the one we introduced.

The soluction was to create a jquery.validate-pt.js with the code to override the validation with the correct one for our format:

$.validator.methods.date = function (value, element) {
    return this.optional(element) || ( /^\d{1,2}[\/-]\d{1,2}[\/-]\d{4}(\s\d{2}:\d{2}(:\d{2})?)?$/.test(value)
        && !/Invalid|NaN/.test(new Date(value.replace("/", "-").split("-")[2], value.replace("/", "-").split("-")[1], value.replace("/", "-").split("-")[0])));
}
Joaquim Franco
  • 248
  • 4
  • 9
  • 2
    I think this might also be helpful - http://geekswithblogs.net/EltonStoneman/archive/2009/10/29/jquery-date-validation-in-chrome.aspx – Henry C Jul 06 '12 at 02:47
  • Hi Joaquim, thanks for posting your solution. Can you advise on where you needed to put the overriding code and how to ensure it does in fact override the validation? – mattpm May 30 '17 at 22:12