ASP MVC DateTime validation error

21,443

Solution 1

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, ..)

Solution 2

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.

Solution 3

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();
   }
});
Share:
21,443
Tom
Author by

Tom

Updated on June 17, 2020

Comments

  • Tom
    Tom almost 4 years

    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.

    • ataravati
      ataravati about 9 years
      Where's your jQuery datepicker? It's most-likely because of your jQuery datepicker's date format.
    • teo van kot
      teo van kot about 9 years
      Also, it's ok that on your View you have EditorFor for model.StartFieldDate and ValidationMessageFor for DataTurno?