10

I have my Entity setup with Data Annotation validation attributes and i am trying to validate it using the static Validator class but i am getting different exceptions, isn't this the right way to do it:

string _ValidateProperty(object instance, string propertyName)
        {
            var validationContext = new ValidationContext(instance, null, null);
            validationContext.MemberName = propertyName;
            var validationResults = new List<ValidationResult>();
            var isValid = Validator.TryValidateProperty(instance, validationContext, validationResults);
            if (isValid)
                return string.Empty;
            return validationResults.FirstOrDefault<ValidationResult>().ErrorMessage;
        }

1 Answer 1

12
+50

You havent stated what Exception you are receiving but it appears you are passing your instance to the TryValidateProperty method when you should be passing the value of the particular property.

Instead of

Validator.TryValidateProperty(instance, validationContext, validationResults);

try

Validator.TryValidateProperty(propertyValue, validationContext, validationResults);

you will have to pass propertyValue down to your method (or use reflection which will be slower)

eg

_ValidateProperty(someObject, "Field1", someObject.Field1);
Sign up to request clarification or add additional context in comments.

1 Comment

Well, you are correct, i don't know where i have read to be careful not to pas the property value to TryValidateProperty but rather the actual object instance, nevertheless i should have done that, Thank you, i will give you the bounty when the site let's me after 12 hours.

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.