验证asp.net MVC不引人注意的验证中的仅时间输入

Vit*_*lik 16 validation asp.net-mvc unobtrusive-validation asp.net-mvc-4

我在页面上有两个单独的字段:一个用于日期,一个用于时间.

这是模型:

[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
public DateTime? StartTime { get; set; }

[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是观点:

@Html.TextBoxFor(m => m.Date, "{0:MM/dd/yyyy}", new { type = "text" })
@Html.TextBoxFor(m => m.StartTime, "{0:hh:mm tt}", new { type = "text", id = "timeStart" })
Run Code Online (Sandbox Code Playgroud)

javascript不引人注目的验证适用于该Date字段,但是当我在StartTime验证节目中输入"11:00 PM"或"11:00 pm"时

"StartTime字段必须是日期"

服务器端验证工作正常,"0:hh:mm tt"它只是有问题的JavaScript.现在我只是禁用了javascript验证,但最终会在这个页面上有它

这可以在"时间"字段中完成吗?

tec*_*osh 16

老实说,实现这一目标的最简单方法是使用正则表达式验证器.这是一个例子.

[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$", ErrorMessage = "Invalid Time.")]
Run Code Online (Sandbox Code Playgroud)

不引人注意的验证应该适用于此表达式.

希望这可以帮到你!

编辑

我修复了正则表达式,由于一些非法字符,它开始在控制台中抛出错误.此外,您将需要此属性的字符串属性包装器,否则它将始终查找有效DateTime.

以下是您应该约束的内容.

模型:

public DateTime? StartTime { get; set; }

[Required]
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$", ErrorMessage = "Invalid Time.")]
public string StartTimeValue
{
    get
    {
        return StartTime.HasValue ? StartTime.Value.ToString("hh:mm tt") : string.Empty;
    }

    set
    {
        StartTime = DateTime.Parse(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@Html.TextBoxFor(m => m.StartTimeValue)
Run Code Online (Sandbox Code Playgroud)

  • @technicallyjosh:很棒的答案!有些读者可能会发现将正则表达式改为`^(0?[1-9] | 1 [0-2]):[0-5] [0-9] [aApP] [mM] $`有帮助.在开头附近的"0?"​​变化使得前导零在10:00之前可选.接近末尾的"[aApP] [mM]"变化显示出像我这样笨拙打字员的怜悯,他们输入aM,Am,pM或Pm. (2认同)

Dim*_*ima 10

DataType.Time属性添加到您的时间字段并使用EditorFors删除格式重复:

模型

    [Required]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [DataType(DataType.Time)]
    public DateTime? StartTime { get; set; }

    [Required]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

视图

    @Html.EditorFor(m => m.Date, new { type = "text" })
    @Html.EditorFor(m => m.StartTime, new { type = "text", id = "timeStart" })
Run Code Online (Sandbox Code Playgroud)