Guilherme David da Costa
Guilherme David da Costa

Reputation: 2368

Simple way of accessing dependent property inside custom data annotation

I have the following properties on my DomainRegistry model:

    [Domain("Extension")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Select extension")]
    public string Extension { get; set; }

Domain it's my custom data annotation and I've tryed everything on my IsValid method to access the value inside extension property.

I have the following in my custom data annotation:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DomainAttribute : ValidationAttribute
{
    public string ExtensionProperty { get; set; }

    public DominioAttribute(string property)
    {
        ExtensionProperty = property;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        var extension = (string) properties.Find(Propriedade, true).GetValue(value);
        if (extension == null) return new ValidationResult("Extension shouldn't be null");
        return null;
    }

I can't seem to get the value from extension inside IsValid method. Anyone have any tip on how to do that? Also I need to get extension as a string value.

Upvotes: 4

Views: 6203

Answers (2)

Luke
Luke

Reputation: 1926

Try this:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty("Extension");

        if (field != null)
        {
            var extensionValue = field.GetValue(validationContext.ObjectInstance, null);

            return extensionValue != null ? ValidationResult.Success : new ValidationResult("Extension shouldn't be null", new[] { validationContext.MemberName });
        }

        return ValidationResult.Success;
    }

Upvotes: 7

nemesv
nemesv

Reputation: 139758

The IsValid method's value parameter contains the actual value of the annotated property so in your case the value of the Name property. To access the actual DomainRegistry instance (to get the value of the Extension property) you should use the validationContext.ObjectInstance property:

 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(validationContext.ObjectInstance);
     var extension = (string)properties.Find(ExtensionProperty, true).GetValue(validationContext.ObjectInstance);
     if (extension == null) return new ValidationResult("Extension shouldn't be null");
     return ValidationResult.Success;
 }

Upvotes: 1

Related Questions