ASP MVC DateTime验证错误 [英] ASP MVC DateTime validation error

查看:63
本文介绍了ASP MVC DateTime验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在asp.net MVC 5中,我有一个显示来自DTO对象的数据的表单:

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; }
}

在我的控制器课上,我有:

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

在视图中,我有:

<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>

而且,对于其他datetime控制器,我具有相同的剃刀代码.我为jQuery UI DatePicker添加了datepicker类.

在表单中,如果我单击创建"按钮,而不修改任何控件,则一切正常. 当我更改最后两个datetime选择器之一,然后单击创建"按钮时,出现验证错误:The field xxxx must be a date.

我不知道问题出在哪里,因为所有控件都是以相同的方式生成的.

解决方案

存在许多潜在问题.

首先,[DataType(DataType.DateTime)][DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]属性仅在使用@Html.EditorFor()时适用,并且用于呈现HTML5日期选择器的浏览器实现(它添加了type="date"属性).由于您使用的是jQueryUI datepicker,因此不需要这些属性.无论如何,如果您确实希望浏览器使用HTML5日期选择器,则该格式必须为DataFormatString = "{0:yyyy-MM-dd}"(ISO格式)才能正常工作.另请注意,HTML5 datepicker仅在现代浏览器中受支持,而在FireFox中完全不受支持( @Html.TextBoxFor(m => m.StartFieldDate, new { @class = "form-control datepicker" })

并在日期选择器脚本中设置格式

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

验证消息可能来自2个问题之一.在客户端,jquery-validate.js使用MM/dd/yyyy格式验证日期.您可以通过添加 jquery全球化或添加以下脚本

来覆盖它以使用dd/MM/yyyy

 $.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' });
 

另一个潜在的问题是服务器端验证.如果服务器区域性不接受格式为dd/MM/yyyy(例如<globalization culture="en-AU" uiCulture="en-AU"/>)的日期,则可能会在服务器上引发验证错误,在这种情况下,您需要为DateTime创建自定义ModelBinder. /p>

旁注:我假设@Html.ValidationMessageFor(m => m.DataTurno, ..)是一个错字(您显示的模型不包含属性DataTurno),并且它确实是@Html.ValidationMessageFor(m => m.StartFieldDate, ..)

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.

解决方案

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

这篇关于ASP MVC DateTime验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆