Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 使用正则表达式进行asp时间跨度验证_Asp.net_Regex_Asp.net Mvc - Fatal编程技术网

Asp.net 使用正则表达式进行asp时间跨度验证

Asp.net 使用正则表达式进行asp时间跨度验证,asp.net,regex,asp.net-mvc,Asp.net,Regex,Asp.net Mvc,在我的一个模型中,我使用了以下属性: [Required(ErrorMessage = "Please enter the duration of the service")] [RegularExpression(@"^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$", ErrorMessage = "Use format HH:MM only")] public TimeSpan Duration

在我的一个模型中,我使用了以下属性:

[Required(ErrorMessage = "Please enter the duration of the service")]
[RegularExpression(@"^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$", ErrorMessage = "Use format HH:MM only")]
public TimeSpan Duration { get; set; }
我使用这个正则表达式来确保duration的格式为HH:mm

每次我尝试以该格式插入值时,都会收到错误消息“Usage format HH:MM only”。删除正则表达式批注后,我成功保存了一个HH:MM(格式字符串),但我意识到它是以另一种格式保存的(HH:MM:SS)。我尝试将正则表达式更改为以下批注:

[RegularExpression(@"^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$", ErrorMessage = "Use format HH:MM:SS only")]
现在我可以用这种格式保存持续时间。当我尝试保存HH:MM格式时,它会自动转换为HH:MM:SS,这就是为什么它在注释检查中失败的原因


我如何处理这个问题?我不想输入某些流的秒数,只想输入小时和分钟。

调用了
TimeSpan
的方法,结果是您描述的格式(即包括秒)。您只需基于
RegularExpressionAttribute
创建自定义的
验证属性
,在
时间跨度

上调用
字符串
时,在其中包含格式
@“hh \:mm”
,我使用了以下注释来解决此问题:

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

谢谢你的建议,但我使用了另一种解决方案