I wrote a validation attribute to make conditional Required's possible.
public class RequiredIfEqualsAttribute : RequiredAttribute
{
private readonly string _otherProperty;
private readonly object _value;
public RequiredIfEqualsAttribute(string otherProperty, object value)
: base()
{
this._otherProperty = otherProperty;
this._value = value;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var valToCompare = validationContext.ObjectInstance.GetType().GetProperty(_otherProperty).GetValue(validationContext.ObjectInstance, null);
if (valToCompare == _value)
{
return base.IsValid(value, validationContext);
}
return null;
}
}
It's easy enough to use:
[EnumDataType(typeof(SomeEnum))]
[Required]
public SomeEnum SomeType { get; set; }
[RequiredIfEquals("SomeType", SomeEnum.A)]
public string A { get; set; }
[RequiredIfEquals("SomeType", SomeEnum.B)]
public string B { get; set; }
I've noticed something odd though. This line:
if (valToCompare == _value)
will actually evaluate to false
, even if valToCompare
and _value
both represent SomeEnum.A
.
Is it because _value
is readonly? When I use the following everything works as expected:
if (valToCompare.Equals(_value))
In this case, if valToCompare
and _value
both represent SomeEnum.A
, the statement will evaluate to true
, as it should.
Who can enlighten me?