输入类型日期的客户端验证不起作用

Mar*_*ijn 7 c# validation unobtrusive-validation asp.net-mvc-3

我有一个包含日期和日期时间字段的表单:

@Html.TextBoxFor(model => model.A, new { @type = "datetime" })
@Html.TextBoxFor(model => model.B, new { @type = "date" })
Run Code Online (Sandbox Code Playgroud)

模型:

public class TestModel
{
  [DataType(DataType.Date)]
  public DateTime A {get;set;}

  [DataType(DataType.Date)]
  public DateTime B {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

通过使用这些输入类型,iPad显示了不错的日期(时间)选择器.使用客户端验证验证字段.对于datetime字段(A),它可以工作,但是日期字段(B)将引发错误:"请输入有效日期." 我该如何解决这个问题?

例子:

  • 此日期时间的iPad(Safari)值有效(根据MVC客户端验证):15 dec.2011 9:20
  • 此日期的iPad(Safari)值无效:15 dec.2011

在iPad上调试代码很难,所以我不知道Safari在设置输入的value属性时如何更改日期格式.

编辑:我发现日期时间格式是通用日期时间格式(yyyy-MM-DDTHH:mmZ),而日期格式是yyyy-MM-dd.可能客户端验证器确实了解通用日期时间,而不是yyyy-MM-dd由于本地化.

spo*_*pot 5

我遇到了完全相同的问题,并且在查看我在iPhone上开发的移动网站时感到非常惊讶。以下问题的讨论为我解决了这一问题。

https://github.com/jzaefferer/jquery-validation/issues/20

另外,为了无缝地解决这个问题,我为Date数据类型创建了以下剃刀编辑器模板:

@model DateTime?
@Html.TextBox("myDate", ViewData.Model.ToIso8601FullDate(), new { type = "date", @class = "text-box single-line" })
Run Code Online (Sandbox Code Playgroud)

以及一种方便的扩展方法,可根据输入type = date规范为 html 5 date输入类型提供喜欢的格式:

public static string ToIso8601FullDate(this DateTime? d)
{
    if (!d.HasValue) return null;

    return d.Value.ToString("yyyy-MM-dd");
}
Run Code Online (Sandbox Code Playgroud)