使用数据注释进行日期时间(日期和时间)验证
我有以下代码:
[DisplayName("58.Date and hour of birth")]
[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy hh:mm")]
[Range(typeof(DateTime), "1/1/2011", "1/1/2016")]
[RequiredToClose]
public object V_58 { get; set; }
我想强制包含时间(格式为 hh:mm)而不仅仅是日期。此代码认为 1/1/2011 有效,但实际上不应该,因为它不包含小时,关于如何表达正确格式的任何线索? (日/月/年 时:分)
I have the following code:
[DisplayName("58.Date and hour of birth")]
[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy hh:mm")]
[Range(typeof(DateTime), "1/1/2011", "1/1/2016")]
[RequiredToClose]
public object V_58 { get; set; }
I want to force the inclusion of time (in format hh:mm) and not only the date. This code considers 1/1/2011 as valid when it shouldn't as it does not containt the hour , Any clue about how to express the correct format ? (dd/mm/yyyy hh:mm)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以编写自己的 ValidationAttribute 并用它来装饰该属性。您可以使用自己的逻辑重写
IsValid
方法。最后,装饰您的属性:
注意:要警惕属性上的多个验证属性,因为如果没有更多自定义,则无法确定它们的评估顺序,随后如果验证逻辑重叠,您的错误消息可能无法准确描述你到底是什么意思,财产有问题(是的,这是一个连续的句子)
You could write your own
ValidationAttribute
and decorate the property with it. You override theIsValid
method with your own logic.And finally, decorate your property:
Note: Be wary of multiple validation attributes on your properties, as the order in which they are evaluated is unable to be determined without more customization, and subsequently if validation logic overlaps, your error messages might not accurately describe what exactly you mean to be wrong with the property (yeah, that's a run-on sentence)
最后用自定义 ValidationAttribute 解决了:
Finally solved with a custom ValidationAttribute :
如果您只是在字符串中传递日期,它会将其视为上午 12:00。如果要在字符串中传递时间,请使用“06/06/2011 7:00 PM”语法。
其他解决方法是将字符串保持原样,将其转换为 DateTime &然后根据您的需要将 AddHours 和/或 AddMinutes 添加到 DateTime 对象。
If you just pass date in a string it will consider it as 12:00 AM. If you want to pass time within a string use "06/06/2011 7:00 PM" syntax.
Other workaround would be to keep your string as is, convert it to DateTime & then AddHours &/or AddMinutes to DateTime object depending on your needs.
此解决方案不允许输入时间 00.00,但可以使用其他值。
但它仅适用于字符串属性。
This solution doesn't allow to input time 00.00, but will work with another values.
But it will work only with string proprety.
DataTime 变量的验证:在获取模型属性的输入时,可以在 set 属性中使用这些验证来检查输入的格式是否正确。
Validation for DataTime Variable : While taking the input for the model properties these validations can be used in the set property to check whether the input is in correct format or not.