Tom
Tom

Reputation: 4107

ASP MVC DateTime validation error

In asp.net MVC 5, I have a form that displays data from a DTO object:

public class FieldDTO
{
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime StartFieldDate { get; set; }

    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime StopFieldDate { get; set; }

    public String FieldName { get; set; }

    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime StartJob { get; set; }

    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime StopJob { get; set; }
}

In my controller class, I have:

public ActionResult Create()
{
   var model = new FieldDTO();
   model.StartFieldDate = DateTime.Now;
   model.StopFieldDate = DateTime.Now;
   model.StartJob = DateTime.Now;
   model.StopJob = DateTime.Now;
   ...
   ...
}

In the view, I have:

<div class="col-md-10">
     @Html.EditorFor(model => model.StartFieldDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
     @Html.ValidationMessageFor(model => model.DataTurno, "", new { @class = "text-danger" })
 </div>

And, I have the same razor code for the other datetime controller. I have added the datepicker class for jQuery UI DatePicker.

In the form, if I click on the "create" button, without modifying any controls, everything works. When I change one of the last two datetime pickers and then click the "create" button, I get the validation error: The field xxxx must be a date.

I don't figure out what the problem is, because all the controls are generated the same way.

Upvotes: 1

Views: 23481

Answers (5)

Just in case this happens to anyone else. I was originally having a validation error because my iOS app in swift was sending unix time. I diagnosed that with a app.using block that read json from the request body. Then, I changed the swift date to iso but it wouldn't work. I spent several hours before I realized, once the diagnostic piece of code read the body content, nothing else could... so it was generating a validation error (but now for a different reason). If anyone happened to peek at your content the same way, remember to remark it out. You can't seek on the Body stream at least in .net core 2.2.

Upvotes: 0

Minh Nguyen
Minh Nguyen

Reputation: 2201

For me just have this code to ovewrite the default Jquery datetime validation:

$(function () {
   $.validator.methods.date = function (value, element) {
    return this.optional(element) || moment(value, "L", true).isValid();
   }
});

Upvotes: 1

Lalji Dhameliya
Lalji Dhameliya

Reputation: 1769

because default format for date time is mm/dd/yyyy. your date consider as a month then it gives error for that you need to add culture format.

        CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;

and in your js file in that you implement datepicker include code like

jQuery.validator.methods["date"] = function (value, element) { return true; }

i have same issue now works fine for me i hope it should help you.

Upvotes: 2

user3559349
user3559349

Reputation:

There a number of potential issues.

Firstly the [DataType(DataType.DateTime)] and [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] attributes are only applicable when using @Html.EditorFor() and are used to render the browsers implementation of a HTML5 datepicker (it adds the type="date" attribute). Since you are using the jQueryUI datepicker, then those attributes are not required. In any case if you do want the browsers HTML5 datepicker, then the format needs to be DataFormatString = "{0:yyyy-MM-dd}" (ISO format) in order to work correctly. Note also the HTML5 datepicker is only supported in modern browsers, and not yet at all in FireFox (refer comparison)

If you using the jQueryUI datepicker then it can be just

@Html.TextBoxFor(m => m.StartFieldDate, new { @class = "form-control datepicker" })

and set the format in the datepicker script

$('.datepicker').datepicker({ dateFormat: 'dd/mm/yy' });

The validation message could be from one of 2 issues. On the client side, jquery-validate.js validates a date using the MM/dd/yyyy format. You can override this to use dd/MM/yyyy by including jquery globalize or add the following script

$.validator.addMethod('date', function (value, element) {
  if (this.optional(element)) {
    return true;
  }
  var valid = true;
  try {
    $.datepicker.parseDate('dd/mm/yy', value);
  }
  catch (err) {
    valid = false;
  }
  return valid;
});
$('.datepicker').datepicker({ dateFormat: 'dd/mm/yy' });

The other potential problem is server side validation. If the server culture does not accept dates in the format dd/MM/yyyy (e.g. <globalization culture="en-AU" uiCulture="en-AU"/>) then a validation error could be thrown on the server, in which case you would need to create a custom ModelBinder for DateTime.

Side note: I assume @Html.ValidationMessageFor(m => m.DataTurno, ..) is a typo (the model your have shown does not include a property DataTurno) and that its really @Html.ValidationMessageFor(m => m.StartFieldDate, ..)

Upvotes: 4

teo van kot
teo van kot

Reputation: 12491

Seems like wrong jQuery datepicker's date format like @ataravati mention.

Try to init datepicker with the dateFormat option, like this:

$(".datepicker").datepicker({ dateFormat: 'dd/mm/yyyy' });

Get to debug or set the dateFormat option, after init, like this:

//this how to get what is it now
var dateFormat = $(".datepicker").datepicker("option", "dateFormat");
//set right format
$(".datepicker").datepicker("option", "dateFormat", "dd/mm/yyyy");

Upvotes: 0

Related Questions