Search code examples
jqueryvalidationasp.net-mvc-4jquery-validateculture

DateTime format according to the culture in MVC


I have an MVC view where I list a dateTime type column named "CreatedOn", the values are formatted like this: 'DD/MM/YYYY HH:MM:SS', When I click on edit link to modify a value I obtain the same format,

When I modify the edited value I get the validation error: "The field CreatedOn must be a date."

My EF model class maps this field as DateTime type.

My database collation is French_CI, the field in the sql server table is smalldatetime type, when I open the table to see the field format I find it like 'YYYY-MM-DD HH:MM:SS'

I verified the default application culture and found "fr-FR", then I added in the web.config file the next code:

<system.web>
  <globalization uiCulture="fr-FR" culture="fr-FR" />
</system.web>

But the issue still remain the same, any idea please ?


Solution

  • jQuery Validate doesn't understand cultures.

    I believe for dates, it just calls the javascript: new Date(value).

    You can fix this with a globalization plugin and a bit of javascript.

    Microsoft wrote a globalization plugin here: https://github.com/jquery/globalize

    Then you want to replace the validation method with something like this:

    $.validator.methods.date = function (value, element) {
      return this.optional(element) || Globalize.parseDate(value);
    }
    

    You probably also want to replace the other methods for numbers etc. - have a look at the bottom of jquery.validate.js for examples.