在 asp.net MVC 不显眼的验证中验证仅时间输入 [英] Validating time-only input in asp.net MVC unobtrusive validation

查看:26
本文介绍了在 asp.net MVC 不显眼的验证中验证仅时间输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two separate fields on the page: one for date and one for time.

这是模型:

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

这是视图:

@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" })

javascript 非侵入式验证在 Date 字段中工作正常,但是当我在 StartTime 中输入11:00 PM"或11:00 pm"时,验证显示

The javascript unobtrusive validation works fine with the Date field however when i enter "11:00 PM" or "11:00 pm" in StartTime the validation shows

字段开始时间必须是日期"

"The field StartTime must be a date"

服务器端验证与 "0:hh:mm tt" 一起工作正常,只是 javascript 有问题.现在我只是禁用了 javascript 验证,但最终希望在此页面上使用它

Server side validation works fine with "0:hh:mm tt" it's only the javascript that has a problem. For now i just disabled javascript validation but would like eventually to have it on this page

这可以用于时间"字段吗?

Can this be done for "time" field?

推荐答案

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

Honestly the easiest way to achieve this is to use a regular expression validator for it. Here is an example.

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

不显眼的验证应该可以很好地处理这个表达式.

The unobtrusive validation should work just fine with this expression.

希望能帮到你!

编辑

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

I've fixed the regular expression which started throwing errors in the console because of some illegal characters. Also, you will need a string property wrapper for this property or else it will always look for a valid DateTime.

以下是您应该绑定的内容.

Below is what you should be binding to.

型号:

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

查看:

@Html.TextBoxFor(m => m.StartTimeValue)

这篇关于在 asp.net MVC 不显眼的验证中验证仅时间输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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