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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With