Search code examples
c#validationasp.net-mvc-4c#-4.0

Get value from basetype of validation context in custom validator


I am trying to write my own validation attribute but I am having trouble getting the value of a property from the inherited class. This is my code:

protected override ValidationResult IsValid(object value, ValidationContext context)
{
    if (context.ObjectType.BaseType == typeof(AddressModel))
    {
        PropertyInfo property = context.ObjectType.BaseType.GetProperty(_propertyName);

        // this is the line i'm having trouble with:
        bool isRequired = (bool)property.GetValue(context.ObjectType.BaseType); 

        return base.IsValid(value, context);
    }

    return ValidationResult.Success;
}

I don't know what I'm meant to pass into the GetValue as it is expecting an object but everything I pass in gives me a property type does not match target exception

I'm having to go to the base type as I am trying to get the value of a property from an inherited class and context.ObjectInstance doesn't include the necessary properties


Solution

  • You can simply cast your object as the AddressModel and use it like that.

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var addressModel = context.ObjectInstance as AddressModel
        if (addressModel != null)
        {
            // Access addressModel.PROPERTY here
    
            return base.IsValid(value, context);
        }
    
        return ValidationResult.Success;
    }
    

    context.ObjectInstance is of object type instead of your model's type because the validation framework wasn't created to explicitly validate your model, but it is the right object instance. Once it's casted you can use it normally.

    As a side note, the reason why you were getting an error with property.GetValue(context.ObjectType.BaseType) is because the GetValue method expects the instance of the object whose property you are calling.