.Net - DataAnnotations - 验证 2 个依赖的日期时间
假设我有以下类:
public class Post
{
public Date BeginDate { get; set; }
[Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs after Begin Date")]
public Date EndDate { get; set; }
}
public class Validate2Dates : ValidationAttribute
{
public Validate2Dates(DateTime a, DateTime b)
{ ... }
public override bool IsValid(object value)
{
// Compare date and return false if b < a
}
}
我的问题是如何使用我的自定义 Validate2Dates 属性,因为我不能这样做:
[Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs before Begin Date")]
我收到以下错误:
非静态字段、方法或对象需要对象引用 属性 '...Post.BeginDate.get' C:...\Post.cs
Let say I got the following classes:
public class Post
{
public Date BeginDate { get; set; }
[Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs after Begin Date")]
public Date EndDate { get; set; }
}
public class Validate2Dates : ValidationAttribute
{
public Validate2Dates(DateTime a, DateTime b)
{ ... }
public override bool IsValid(object value)
{
// Compare date and return false if b < a
}
}
My problem is how to use my custom Validate2Dates attribute because I can't do that:
[Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs before Begin Date")]
I got the following error:
An object reference is required for the non-static field, method, or
property '...Post.BeginDate.get' C:...\Post.cs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用这样的属性。属性参数仅限于常量值。
我认为更好的解决方案是在您的类上提供一个方法来实现此检查,并且可以通过您喜欢的某些业务逻辑验证接口进行调用。
You can't use an Attribute like that. Attribute parameters are restricted to constant values.
Imo the better solution would be to provide a method on your class that implements this check and can be called through some business logic validation interface of your liking.
答案是肯定的,您可以做您想做的事情,但不能按照您当前的方式做。 (顺便说一句,我刚刚注意到这个问题已经得到了很好的回答已经所以我想我至少应该快速引用它。)
基于上面的链接...
[Validate2Date(BeginDate) , EndDate, ...
变为
[Validate2Date(StartDate = "BeginDate", EndDate = "EndDate", ...
然后您将重写 IsValid() 并反映必要的来自链接
The answer is yes, you can do what you're trying to do, just not the way you're currently doing it. (Incidentally, I just noticed that this question has been answered very well already so I thought I'd at least drop a quick reference to it.)
Based on the link above...
[Validate2Date(BeginDate, EndDate, ...
becomes
[Validate2Date(StartDate = "BeginDate", EndDate = "EndDate", ...
You'll then override IsValid() and reflect over the the necessary properties to perform the comparison. From the link