Question

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

Was it helpful?

Solution

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])));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top