I am validating a field based on another field using custom validation in MVC and I came across this implementation:
public class RequiredIfAttribute : ValidationAttribute
{
private String PropertyName { get; set; }
private String ErrorMessage { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
{
this.PropertyName = propertyName;
this.DesiredValue = desiredvalue;
this.ErrorMessage = errormessage;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
And I have a simple class defined as follows:
public class Person
{
public int PersonID { get; set; }
public string name { set; get; }
[RequiredIf("name","","Address is required")]
public string addr { get; set; }
}
When I run the page, I get a Object reference not set to an instance of an object. error but changing the line to [RequiredIf("name","John","Address is required")] yields expected results. My question is, how do you use it to check if the field is empty.
I have also tried changing the line to [RequiredIf("name",null,"Address is required")] but I get the same error.