MVC3 Validation with ComponentModel.DataAnnotations for UK date format (also using jquery ui datepicker)
asp.net-mvc-3, c#, data-annotations, entity-framework, validation
Solution
Right, the problem was with the jquery validate scripts insisting on using the US datefomat. I will restrain my self from going on a proper rant about the fact that the majority of the world uses dd/mm/yyyy though.
Anyway, eventually i found the answer to my woes in a comment to an answer of a similar question, the author of which kindly wrote a blog post about how he solved the issue.
Basically I have used the jquery globalize script and just set the culture to `en-GB`. I should mention that in his blog he doesn't mention where to put the bit where you specify the culture, so i just shoved in in script tags in the page under the references to the globalization scripts:
<script src="@Url.Content("~/Scripts/globalize.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/globalize.culture.en-GB.js")" type="text/javascript"></script>
<script type="text/javascript">
Globalize.culture("en-GB");
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value);
};
</script>
Problem
I see there are some similar questions to this, but none solve my issue. I am working on an MVC3 app with Entity Framework 4.3. I have a UK date field that i plan to allow the user to edit using the Jquery UI datepicker (which i got working thanks to this blog). Fortunately for me this blog includes instructions on making the datepicker using UK format, however, the EF validation is still telling me that i need to enter a valid date format. Wierdly it doesn't prevent me from submitting the date to the DB its just the unobtrusive validation kicking in and displaying the message. At the moment I have the following data annotation: ``` [DataType(DataType.Date)] public System.DateTime Module_Date { get; set; } ``` but i have also tried adding: ``` [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")] ``` which had no effect at all. I hope some one has a solution because i don't fancy turning off the unobtrusive validation to stop this error message. Thanks EDIT following @Iridio answer, i looked into adding a Model Binding, and indeed from the few posts like this one that i read it seemed to be the right thing to do, but what i have come up with has no effect. here is what i have tried: ``` public class DateTimeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture); return date; } } ``` with this in the `Application_Start()` method of the `Global.asax.cs` file: ``` ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder()); ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder()); ```