views:

225

answers:

2

I'm using ASP.NET MVC and implementing custom validation via custom attributes/data annotations on my models.

Is it possible to access a property on an object's parent class inside my custom attribute?

public class MyModel
{
    [MyCustomValidator]
    public string var1 {get; set;}
    public string var2 {get; set;}
}

Note: Using asp.net mvc

public class MyCustomValidatorAttribute : ValidationAttribute
{
    public bool override IsValid(Object value)
    {  
          // somehow get access to var2 in the MyModel
    }
}

So basically, making validation check another property for a specific value. I tried to pass var2's value as a parameter to MyCustomValidator but that doesn't work.

+3  A: 

No, basically. After a hunt through reflector, you only have access to the value of the member being tested - not the containing object or even the member-info of the property/field/whatever.

Which I agree is very limiting and frustrating, but it looks like this is fixed in 4.0 - my previous reply hinted at this, but in 4.0 there is an IsValid overload that accepts a ValidationContext, which provides this infomation via ObjectInstance.

Marc Gravell
Doesn't `ObjectInstance` refer to the object that is decorated with the said attribute? Also, I can't seem to override Validate, it doesn't show up. Only IsValid(object value) shows up.
Baddie
Side note: Using asp.net mvc
Baddie
@Baddie - I'll take another look later...
Marc Gravell
When I do `protected override ValidationResult IsValid(object value, ValidationContext validationContext)`, validationContext is always null.
Baddie
@Baddie - well that is even *more* frustrating. You could log as an issue on "connect"?
Marc Gravell
+1  A: 

Apparently, MVC 2 Validation doesn't support validationContext because MVC 2 targets DA 3.5. I'm not sure if this is still the case with MVC 2 RC, I'm using VS 2010 with MVC 2 Preview 1.

Taken from Brad Wilson's post at http://forums.asp.net/p/1457591/3650720.aspx

There is no validation context in the 3.5 SP1 version of DataAnnotations, which is what MVC 2 targets. The [CustomValidation] attribute is also an artifact of DA4.0, so to write a custom validation, you need to create a new validation attribute derived from ValidationAttribute

Baddie