ASP MVC DateTime validation error

前端 未结 5 1726
轮回少年
轮回少年 2021-01-26 08:28

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

public class FieldDTO
{
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInE         


        
5条回答
  •  难免孤独
    2021-01-26 08:50

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

提交回复
热议问题