验证时间仅在asp.net MVC不引人注目的验证输入 [英] Validating time-only input in asp.net MVC unobtrusive validation

查看:183
本文介绍了验证时间仅在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的不显眼的审定工作正常与日期字段但是当我在输入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?

推荐答案

老实说实现这一目标的最简单方法是使用常规的前pression验证它。下面是一个例子。

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.")]

在不引人注目的验证应该只是这个前pression罚款。

The unobtrusive validation should work just fine with this expression.

希望这可以帮助你!

修改

我已经解决了常规的前pression始于扔在控制台,因为一些非法字符的错误。此外,您将需要一个字符串属性包装该物业,否则它会一直寻找一个有效的的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天全站免登陆