.Net - DataAnnotations - 验证2个相关的DateTime

时间:2010-01-19 01:27:26

标签: c# validation .net-3.5 data-annotations

假设我有以下课程:

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

我收到以下错误:

  

非静态字段,方法或者需要对象引用   property'... Post.BeginDate.get'C:... \ Post.cs

2 个答案:

答案 0 :(得分:0)

你不能使用那样的属性。属性参数限制为常量值。

Imo更好的解决方案是在您的类上提供一个实现此检查的方法,并且可以通过您喜欢的某个业务逻辑验证接口调用。

答案 1 :(得分:0)

答案是肯定的,你可以做你想做的事情,而不是你现在的做法。 (顺便说一句,我只是注意到这个question已经得到了很好的回答,所以我想我至少会快速提及它。)

基于上面的链接...

  1. 您需要编写自定义验证程序(您已经完成)
  2. 您需要在级别装饰您的模型,而不是属性级别
  3. 您不会将属性本身用作参数 - 相反,您只需将它们引用为通过反射查找的字符串
  4. [Validate2Date(BeginDate, EndDate, ...

    变为

    [Validate2Date(StartDate = "BeginDate", EndDate = "EndDate", ...

    然后,您将覆盖IsValid()并反映必要的属性以执行比较。 From the link

    .... 
            var properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
    ....