gpt4 book ai didi

asp.net - DateTime 属性上的 DataAnnotations

转载 作者:行者123 更新时间:2023-12-04 06:50:08 24 4
gpt4 key购买 nike

我的模型中有一个 DateTime 属性,我想使用 DataAnnotations 验证它。

在我看来,我想将该日期时间作为天数(例如“3”)而不是日期时间(例如“7/14/2010”)。如果用户在 View 中输入“3”,则 DataAnnotation 发现它无效——这就是问题所在。

在这种情况下我有哪些选择?

非常感谢您的帮助。

最佳答案

听起来您为这项工作使用了错误的类型。以“天”为单位的度量是时间跨度,而不是日期时间。我会更新您的模型以将该属性公开为 TimeSpan。您可以使用自定义验证器进行验证,如下所示:

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]
public class TimeSpanAttribute: ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is TimeSpan)
{
return true;
}
else if (value is String)
{
TimeSpan result;
return TimeSpan.TryParse((string)value, out result);
}

return false;
}
}

关于asp.net - DateTime 属性上的 DataAnnotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3251791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com