ASP MVC 5 Error checking date format

In my ASP MVC 5 web application, I need to display the date in a specific format. When the page loads, the text is formatted correctly. But if you are editing a value or just trying to post a message, a validation error is displayed:

enter image description here

The field is defined as follows:

@*Creation*@ <div class="form-group"> @Html.LabelFor(model => model.Creation, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Creation, "{0:dd/MM/yyyy}", new { @class = "form-control"}) @Html.ValidationMessageFor(m => m.Creation) </div> </div> 

The viewmodel property is defined as:

  [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [Display(Name = "Creation", ResourceType = typeof(Resources.Resources))] public DateTime Creation { get; set; } 

The screenshot was taken using the Firefox browser. If I do the same on Edge, the check will pass, but the rate of this property in the post method is invalid (the default date value).

How can I fix this problem?

+6
source share
1 answer

The problem is that behind the scenes, validation is performed by jQuery. So, the key is to tell jQuery validator that you will use the dd / MM / yyyy format.

There are several ways to do this. The easiest way is to simply override the validator function (for dates) with the simpe setting:

 jQuery(function ($) { $.validator.addMethod('date', function (value, element) { $.culture = Globalize.culture("en-AU"); var date = Globalize.parseDate(value, "dd/MM/yyyy", "en-AU"); return this.optional(element) || !/Invalid|NaN/.test(new Date(date).toString()); }); }); 

An alternative would be to use a globalization library for jQuery. There is a globalization library that you can use here .

When you have the library, include these files:

 globalize.js globalize.culture.en-AU.js 

Then override the validator function:

 <script type="text/javascript"> $(function () { $.validator.methods.date = function (value, element) { Globalize.culture("en-AU"); // the UK format return this.optional(element) || Globalize.parseDate(value) !== null; } }); </script> 
+5
source

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


All Articles