2

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.

2 Answers 2

2

This seems to work:

protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            if (value != null) { return ValidationResult.Success; }

            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue == null) {
               return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
Sign up to request clarification or add additional context in comments.

Comments

0

You did not post the actual Person instantiations that you're testing, so I'm just guessing: make sure that proprtyvalue of PropertyName is not null before trying to call ToString() on it. So your Person.Name cannot be null!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.