Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC set validation date format fails on Chrome

Tags:

asp.net-mvc

I'm having problems with setting validations date format Chrome in asp.net mvc, for other browsers like IE,Firefox works correctly .

I have defined dates in my model like next code:

[Required]
[Display(Name = "Data fi publicació")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime PublishingEndDate { get; set; }

And in my views :

@Html.TextBoxFor(model => model.PublishingEndDate)
@Html.ValidationMessageFor(model => model.PublishingEndDate)

The problem It seems that @Html.ValidationMessageFor, validates the date with format MM/dd/yyyy, but what I want is to validate with european format dd/MM/yyyy. How can I change default culture validations format date to dd/MM/yyyy ?

Thanks for your help

like image 470
Marc Cals Avatar asked Oct 11 '12 18:10

Marc Cals


2 Answers

Finally I discover the problem only affects Chrome, with IE, Firexfox it works perfectly, it seems is a chrome bug, I found the solution in http://forums.asp.net/t/1729179.aspx/1

The validator method of jquery has to be override using the following code:

$(document).ready(function () {
    $('.calendarPicker').datepicker({ dateFormat: "dd/mm/yy" });

$.validator.addMethod('date',
    function (value, element, params) {
        if (this.optional(element)) {
            return true;
        }

        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });
});
like image 175
Marc Cals Avatar answered Sep 20 '22 14:09

Marc Cals


Be sure you've set your culture in web.config. This will use the appropriate date and number formatting for the culture chosen.

http://msdn.microsoft.com/en-us/library/bz9tc508(v=vs.100).aspx

like image 24
Ben Finkel Avatar answered Sep 21 '22 14:09

Ben Finkel