Custom model validation of dependent properties using Data Annotations

Posted by Darin Dimitrov on Stack Overflow See other posts from Stack Overflow or by Darin Dimitrov
Published on 2010-02-17T12:30:50Z Indexed on 2013/11/04 9:55 UTC
Read the original article Hit count: 298

Since now I've used the excellent FluentValidation library to validate my model classes. In web applications I use it in conjunction with the jquery.validate plugin to perform client side validation as well. One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place.

For this reason I'm looking for an alternative. There are many examples out there showing the usage of data annotations to perform model validation. It looks very promising. One thing I couldn't find out is how to validate a property that depends on another property value.

Let's take for example the following model:

public class Event
{
    [Required]
    public DateTime? StartDate { get; set; }
    [Required]
    public DateTime? EndDate { get; set; }
}

I would like to ensure that EndDate is greater than StartDate. I could write a custom validation attribute extending ValidationAttribute in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the model instance:

public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // value represents the property value on which this attribute is applied
        // but how to obtain the object instance to which this property belongs?
        return true;
    }
}

I found that the CustomValidationAttribute seems to do the job because it has this ValidationContext property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1?


UPDATE:

It seems that FluentValidation already supports clientside validation and metadata in ASP.NET MVC 2.

Still it would be good to know though if data annotations could be used to validate dependent properties.

© Stack Overflow or respective owner

Related posts about validation

Related posts about .net-3.5