开发者

.Net - DataAnnotations - Validate 2 dependent DateTime

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 p开发者_如何学运维roperty '...Post.BeginDate.get' C:...\Post.cs


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.


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...

  1. You'll need to write a custom validator (which you've already done)
  2. You'll need to decorate your model at the class level, not the property level
  3. You won't be using the properties themselves as parameters - instead you'll simply reference them as strings to be looked up via reflection

[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

.... 
        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);
....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜