Validating MVC3 with ComponentModel.DataAnnotations for UK date format (also using jquery ui datepicker)

I see that there are some similar questions, but nobody solves my problem.

I am working on an MVC3 application with Entity Framework 4.3. I have a date field in the UK that I plan to allow the user to edit using the jQuery UI datepicker (which I received thanks to this blog ).

Luckily for me, this blog post contains instructions on creating a datepicker using the UK format, however the EF check still tells me that I need to enter the correct date format. Wierdly, this does not stop me from presenting the date in the database, it is just an unobtrusive confirmation that inserts and displays a message.

At the moment, I have the following data annotation:

[DataType(DataType.Date)] public System.DateTime Module_Date { get; set; } 

but I also tried to add:

 [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")] 

which had no effect. I hope someone has a solution because I don't want to turn off unobtrusive checking in order to stop this error message.

thanks

EDIT

after @Iridio's answer, I looked into adding a binding to the model, and indeed from a few posts like this one that I read seemed to be correct, but what I came up with has no effect. here is what i 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()); 
+6
source share
6 answers

That's right, the problem was with jquery validation scripts that insisted on using a date in the USA. I restrain myself from talking properly that most people use dd / mm / yyyy.

In any case, in the end, I found the answer to my problems in a comment on the answer to a similar question , the author of which kindly wrote a blog post about how he solved the problem.

I basically used a jquery globalize script and just set the culture to en-GB . I should mention that in his blog he does not mention where to put the bit, where you indicate the culture, so I just went into the script tags on the page under the links 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> 
+4
source

You need to write your own ModelBinder for the DateTime type.

This is a binder that I wrote for a similar problem, but with the Decimal type (you might need this). you must understand the idea and adapt it to your needs

 public class DecimalModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); ModelState modelState = new ModelState { Value = valueResult }; object actualValue = null; try { actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture); } catch (FormatException e) { modelState.Errors.Add(e); } bindingContext.ModelState.Add(bindingContext.ModelName, modelState); return actualValue; } } 

Then in global.asax you register your binder and you're done

 protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); //Here you tell how to hendle the specific type ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); } 

UPDATE

After your clarification, this answer should help

+1
source

I believe there is a bug in the jQuery ui datepicker script version that comes with the mvc3 card (jquery-ui-1.8.11.js).

If you specify the date in uk format (as is the case with blogs):

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

then jquery-ui-1.8.11.js seems to have a problem with checking the date and keeps asking for a valid uk date (but the check is random). If you change the date format to "mm / dd / yy" then this problem will disappear, but this is not suitable for uk dates.

The problem was resolved in a later version of this library, so download the latest version (I believe 1.8.18 at the time of writing) or the cdn link:

 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js" type="text/javascript"></script> 
+1
source

Actually I found the best solution here .... by #fretje

Override jquery date

I changed his / her code a bit so that it can accept date formats, like May 30, 2012.

 $(function () { $.validator.addMethod( "date", function (value, element) { //Added to validate dates like 31 May 2012 if (value.split('/').length === 1) return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); var bits = value.match(/([0-9]+)/gi), str; if (!bits) return this.optional(element) || false; str = bits[1] + '/' + bits[0] + '/' + bits[2]; return this.optional(element) || !/Invalid|NaN/.test(new Date(str)); }, "Please enter a date in the format dd/mm/yyyy" ); $global.init(); }); 
+1
source

I had this problem only now, it took several hours to find out the cause. I'm not saying that this is your problem, but after I spent hours switching globalization to everything, etc., I thought I would post this problem here for any people who are struggling like me.

Anyway, the problem in my project is actually not what I thought. I graced the [DataAnnotationsExtentions.Date] property, which turns out to twist the client side check in chrome when it comes to localization (i.e. if you want the day after the 12th in England), although it seems like it works great in other browsers. As soon as I deleted it, it worked

0
source

The problem is that for some reason, if you put the "date" class in the text box, Chrome just goes crazy, as described here in this blog . I had the same problem and I just changed the class name to customDate and solved it.

0
source

Source: https://habr.com/ru/post/913116/


All Articles