1

In an asp.net MVC application, I have the following property:

...
public System.DateTime StartTime { get; set; }
...

And, in a view (in a form):

<div class="form-group">
   @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
      @Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(model => model.StartTime, "", new { @class = "text-danger" })
   </div>
</div>

in the javascript:

$("#StartTime").datepicker({
    dateFormat: "dd/mm/yy",
});

I get the following error with the default jquery validation of asp.net MVC:

The field StartTime must be a date.

I can handle the date in dd/MM/YYYY format without any error in asp.net MVC?

ataravati
  • 8,891
  • 9
  • 57
  • 89
Tom
  • 4,007
  • 24
  • 69
  • 105
  • Is the last sentence a question or a statement? – ataravati Dec 14 '15 at 15:43
  • 1
    Your error is occurring either because your server culture does not accept dates in the format `dd/MM/yyyy` or because you have not modified the jQuery validator (by default it will validate dates based in `MM/dd/yyyy`). Refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) for some options –  Dec 14 '15 at 21:54

1 Answers1

0

I had the same problem, and the key of the issue was the dateFormat. If you use default format there is no problem when submitting, but if you change it then there are problems submitting it.

The solution I found was to use altField and altFormat. With datepicker you can have a format for the showing value and an alternative hidden field (altField) with a different format (altFormat). To use it do something like:

    $("#StartTime").datepicker({
    dateFormat: "dd/mm/yy",
    altField: $(this).val(),
    altFormat: "M/dd/yy"
    });
Samuel A
  • 81
  • 9