我正在构建一个调度屏幕,需要显示一个时间字段,供用户输入日程的时间。
我不确定这是否是最好的选择,但我使用的是一个TimeSpan的领域。为了验证输入,我想使用Range属性和DisplayFormat属性。
当我调试并输入一个看似有效的值时,Range属性表示超出范围的错误。有人能看出我做错了什么吗?TimeSpan是这种用法的合适类型吗?任何帮助都是非常感谢的。
模型类:
public class Schedule
{
public Schedule()
{
this.ScheduleTime = new TimeSpan(0, 0, 0);
}
/// <summary>
/// The time of day for the schedule to run
/// </summary>
[Required, DataType(System.ComponentModel.DataAnnotations.DataType.Time),
Display(Name = "Schedule Time", Description = "Number of Hours and Minutes after Midnight Central Timezone"),
DisplayFormat(DataFormatString = @"{0:hh\:mm\:ss}", ApplyFormatInEditMode = true),
Range(typeof(TimeSpan), "00:00", "23:59")]
public TimeSpan ScheduleTime { get; set; }
}错误消息:

发布于 2013-09-04 23:14:41
你知道那些时候你会问一个问题,在回答之后不久就会出现在你面前吗?这对我来说是其中之一。
我找到了这样的帖子:why does ASP.Net MVC Range Attribute take a Type?
它将问题描述为jQuery无法处理范围表达式,因此客户端验证将无法工作,但服务器端验证将运行。
因此,我用javascript删除了这个字段的客户端验证:
<script>
$(document).ready(function () {
$("#ScheduleTime").rules('remove', 'range');
});
</script>现在,在检查控制器中的ModelState.IsValid时,验证工作正常。
发布于 2018-02-22 23:13:27
我在寻找类似的问题时发现了这个问题,我想对ASPNET 2和JQuery v2.2.0中范围验证工作良好的记录说一句。
[Range(typeof(TimeSpan), "00:00", "23:59")]发布于 2015-01-29 15:04:30
我知道这是一个旧的帖子,但是我能够使用正则表达式而不是像这样的范围验证来保持客户端验证:
[Display(Name = "Schedule Time ")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm}")]
[RegularExpression(@"((([0-1][0-9])|(2[0-3]))(:[0-5][0-9])(:[0-5][0-9])?)", ErrorMessage = "Time must be between 00:00 to 23:59")]
public System.TimeSpan? ScheduleTime { get; set; }https://stackoverflow.com/questions/18624766
复制相似问题