Edition:
I leave this question for the sake of archiving but tbh I should probably delete it. It was my complete fault, I was doing several things wrong. First of all I reused the code from a RequiredIf validation but I should remove the _innerAttribute and the most inner if related to it that I forgot to do. And the main thing is that I was trying to compare an enum to a string and that's why it was failing but the code actually works fine if I pass to the constructor the appropriate enum member. I was misunderstanding completely the behaviour of object, casts...
End of edition
I'm trying to write a custom validation attribute that disallows a field to be set to a particular value if another one is not null. I've written this (I ommit the part for implementing the IClientVAlidatable)
public class NotAllowedIfNotNullAttribute : ValidationAttribute, IClientValidatable
{
private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object NotAllowedValue { get; set; }
public NotAllowedIfNotNullAttribute(string dependentProperty, object notAllowedValue)
{
DependentProperty = dependentProperty;
NotAllowedValue = notAllowedValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var typedValue = CastValue(value, _valueType)
;
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentvalue != null && value.Equals(NotAllowedValue)))
{
if (!_innerAttribute.IsValid(value))
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
//.....
}
My problems is value.Equals(NotAllowedValue)
, how could I get the value casted to the notAllowedValue type? I've tried to pass the type as a paremeter but I would need to work more in that approach as I had no luck for the moment
Thanks!