views:

320

answers:

1

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
A: 

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.

Anton