MVC3 Unobtrusive Date Check to Custom Formatted Date

I have a date field (I use jquery ui datepicker) in a form that I formatted, for example:

ViewModel

[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)] public DateTime FooDate { get; set; } 

View

 @Html.EditorFor(m => m.FooDate) 

This correctly shows the date as I want it, for example. 09-Nov-2011

The problem I get occurs when I click submit. He keeps telling me that the date is invalid .... It really is, you stupid thing!

Is there any way I can get jquery / unobtrusive javascript to ignore this field or allow this format? For now, the only way to get the form to work is if I don't format the date or use {0: d} as the date format for it.

Edit : I created a completely separate layout + view + controller + model to test this stupid thing. Still not working in IE / Safari. I have the latest jquery.validate / unobtrusive files from nuget.

My layout empty. It just downloads the following files:

 "jquery-1.7.min.js" "jquery-ui-1.8.16.min.js" "jquery.validate.min.js" "jquery.validate.unobtrusive.min.js" 

My TestViewModel is simple:

 public class TestViewModel { [Display(Name = "Test Date:")] [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)] public DateTime? TestDate { get; set; } } 

My TestController is as follows:

 public class TestController : Controller { public ActionResult Index() { var m = new TestViewModel(); m.TestDate = DateTime.Now; return View(m); } } 

My view:

 @using (Html.BeginForm()) { ViewContext.FormContext.ValidationSummaryId = "valSumId"; @Html.ValidationSummary(false, "The following errors were found:"); @Html.AntiForgeryToken() @Html.LabelFor(m => m.TestDate) <input type="date" id="TestDate" value="@Model.TestDate.Value.ToString("dd/MMM/yyyy")" /> <input type="submit" /> } 

No work.

Do you know what this bothers? If I change TestDate to a string, it still fails.

+7
source share
10 answers

So it looks like jquery.validate.unobtrusive has problems with input type="date" . This should be a bug that only occurs in IE and Safari.

When I deleted the unobtrusive js file, it presented the form in order. When I added the unobtrusive js file back and changed the input type to text, it worked.

Annoying mistake. Must be fixed.

+3
source

I think there is a problem with hyphens ("-") in the format string:

 [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)] 

Unobtrusive checking doesn't seem to accept a hyphen to format the default date.

In my case, I had to add a custom method on the client side:

 $.validator.methods.date = function (value, element) { var s = value; s = value.replace(/\-/g, '/'); return this.optional(element) || !/Invalid|NaN/.test(new Date(s)); }; 

as implemented here

+4
source

There are two things here:

  • Client side validation
  • Server side validation

Both must use the same format for this to work. First, let's look at server side validation. You can write your own mediator for DateTime fields, which will use the format specified for display when binding them back. Here is an example of such a connecting device .

Next, we must deal with client-side validation. To do this, you can write a custom rule that will be bound to these elements:

 <script type="text/javascript"> $.validator.addMethod( 'myDateFormat', function (value, element) { // TODO: put your validation logic here that will parse the string // and validate it return false; }, 'Please enter a date in the format dd-MMM-yyyy' ); $(function () { // we attach the custom validation rule to the given input element $('#FooDate').rules('add', 'myDateFormat'); }); </script> 

You can also use adapters with a custom attribute .

+2
source

In my case, I use a text box for the date, so it did not cause a problem to validate jquery:

  <div class="editor-field"> @Html.TextBox("ExpiryDate", String.Format("{0:ddd, dd MMM yyyy}", DateTime.Now), new { id = "expirydate" }) @Html.ValidationMessageFor(model => model.ExpiryDate) </div> 

So why don't you try formatting a date like this instead of using the input = date type?

Hope this help :)

+1
source

This is actually not a bug in the browser, client validation problems can occur due to the MVC error (even in MVC 5) in jquery.validate.unobtrusive.min.js, which does not accept the date / date-time format in any way . Unfortunately, you must solve this manually.

My final decision:

You should enable this before:

 @Scripts.Render("~/Scripts/jquery-3.1.1.js") @Scripts.Render("~/Scripts/jquery.validate.min.js") @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") @Scripts.Render("~/Scripts/moment.js") 

You can install moment.js using:

 Install-Package Moment.js 

And then you can finally add a fix for the date format syntax:

 $(function () { $.validator.methods.date = function (value, element) { return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid(); } }); 
+1
source

According to lukyer, jquery.validate * .min.js files may encounter problems, especially if you added your own validation to these files. The simple answer I found that worked for me when the final release system was unable to check the dates in IE (Chrome worked without problems) was simply to remove the pre-packaged miniature verification files in general and let the beast deal with this for having β€œfiles.” The only shame was that I did not associate a more vivid answer to the solution before ...

(I would probably post this as a comment, but apparently I haven't gotten enough reputation yet: I need to try harder!)

+1
source

Have you tried just changing the type:

 @Html.TextBoxFor(model => model.startDate, new { @class = "date" }) 

I had the same problem with EditorFor ... so I changed it to this and then applied my jquery datepicker to the 'date' class added to the text box.

0
source

Just wanted to make a little comment on this line if anyone else has problems with this later:

 <input type="date" id="TestDate" value="@Model.TestDate.Value.ToString("dd/MMM/yyyy")" /> 

In some cases (at least in my case earlier) this translates to this format: β€œ01.01.2012”, because with some cultures you cannot specify such slashes to actually get formatted in this way, it just turns them in points, so I had to write:

 @Model.TestDate.Value.ToString("dd\/MMM\/yyyy"); 

What gave me the 01/01/2012.

0
source

Pretty old this stream. Just landed here, having similar problems. In another thread, I read that there might be a problem with version incompatibility with all of these * .js libraries that were somehow in Validation. Perhaps the following link might help other landig readers here: https://stackoverflow.com/a/316618/

Hope this helps

0
source

I had the same problem, it made me bananas! Basically, the mvc check will always display DateTime objects that require values ​​in the text box. What for? Because it is directly related to a DateTime object. Should you declare your ViewModel with? character, you make it null. This way you will not require verification:

 public class MyViewModel { DateTime? StartDate { get; set; } } 

Hope this helps

-one
source

All Articles