我正在构建一个计划屏幕,需要显示一个时间字段,供用户输入计划的时间。
我不确定这是否是最好的选择,但我正在使用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; }
}
错误消息:
答案 0 :(得分:4)
我知道这是一篇旧帖子,但我能够使用正则表达式而不是范围验证来保持客户端验证,如下所示:
[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; }
答案 1 :(得分:3)
我在寻找类似问题时发现了这个问题,我想说的是,范围验证在ASPNET Core 2和JQuery v2.2.0中运行良好。
[Range(typeof(TimeSpan), "00:00", "23:59")]
答案 2 :(得分:1)
你知道那些你提出问题的时间,答案刚出现之前不久吗?这对我来说就是其中之一。
我找到了这个帖子: why does ASP.Net MVC Range Attribute take a Type?
其中描述了jQuery无法处理Range表达式的问题,因此客户端验证将不起作用,但服务器端验证将会起作用。
所以我用javascript删除了这个字段的客户端验证:
<script>
$(document).ready(function () {
$("#ScheduleTime").rules('remove', 'range');
});
</script>
现在,在检查控制器中的ModelState.IsValid
时,验证工作正常。