Retrieving Model MetaData from within a validation attribute

.net, asp.net-mvc-4, c#, validation

Solution

Here is what you can do:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var model = validationContext.ObjectInstance;

    var displayName = validationContext.DisplayName;
    var propertyName = model.GetType().GetProperties()
        .Where(p => p.GetCustomAttributes(false).OfType<DisplayAttribute>().Any(a => a.Name == displayName))
        .Select(p => p.Name).FirstOrDefault();
    if (propertyName == null)
        propertyName = displayName;

    var property = model.GetType().GetProperty(propertyName);
    var uppercaseAttribute = property.GetCustomAttributes(typeof(UppercaseAttribute), false).SingleOrDefault() as UppercaseAttribute;

    if (uppercaseAttribute != null)
    {
        // some code...
    }

    // return validation result...
}

For some reason, validationContext.MemberName is always null, so you have to get the property name based on its display name.

Problem

Using MVC4 I need to retrieve the current `ModelMetadata` from within a custom `ValidationAttribute`. The reason for this is that the Validation Attribute needs to be aware of which other attributes are attached to the specific property in which is being validated. In specific it much check whether the property has an `UppercaseAttribute` attached to it; if this is the case then it will perform a different path of logic. If it is possible to grab the `ModelMetadata` from within the `ValidationAttribute`, I will use the following code to check for it: ``` ModelMetadata.ContainerType .GetProperty(ViewData.ModelMetadata.PropertyName) .GetCustomAttributes(typeof(UppercaseAttribute), true) ``` Firstly, is it possible to retrieve the `ModelMetadata` from within a custom `ValidationAttribute`. Secondly, is the above code the best practice for checking whether a property has a specific attribute attached to it.

Original source