This morning I wasted about 4 hours on a bug that turned out to be a browser issue rather than a code one.
When using Chrome I noticed that my datetime validation in MVC was failing. This validation was working perfectly in Internet Explorer and Firefox. So what was going on?
First let me explain my setup. I had a model with the following Data Annotations on it:
[Required]
[DataType(DataType.DateTime)]
[DisplayName("Start Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
Next up my View had the following line to display my date textbox:
@Html.TextBox("", Model.StartDate, new { @class = "datepicker" })
All of the above looks ok and works exactly as expected on Firefox and Internet explorer but Chrome was still failing on validation and would not let me submit the form.
I searched around and noticed that this appears to be a known issue with Chrome and how it interprets globalization settings. Rather than picking up the settings from my app it was always using its own settings which were en-US so unless the date format was 'yyyy-MM-dd' or 'MM-dd-yyyy' then it would fail.
It turns out that I have to add the following line of JavaScript to tell the browser to ignore the JavaScript validation for the date fields. It will still get picked up on server side so this was not a deal breaker for me. Simply add:
$.validator.methods["date"] = function (value, element) { return true; }
You can read more about this over on Stackoverflow.com
Hopefully this post will save someone else from wasting as much time on this issue as I've just wasted!
Member discussion