Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Guilherme David da Costa Avatar asked Sep 03 '25 14:09

Guilherme David da Costa


1 Answers

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;
    }
like image 103
Luke Avatar answered Sep 05 '25 15:09

Luke