How to validate object recursively?
-
Friday, April 27, 2012 9:52 PM
How to validate all the properties of class recursively using the Validator.TryValidateProperty(……) method.
I found an article here that shows how to do recursive validationhttps://github.com/reustmd/DataAnnotationsValidatorRecursive/tree/master/DataAnnotationsValidator/DataAnnotationsValidator
But he is using Validator.TryValidateObject(…) method..for some reason I would like to use Validator.TryValidateProperty(……) mthod.
Below is my NON working code, im not sure. what im missing hereprivate bool TryValidateProperty(object obj, object contextObject, ICollection<ValidationResult> results) { return Validator.TryValidateProperty(obj, new ValidationContext(contextObject, null, null), results); } private bool TryValidatePropertyRecursive(object obj, List<ValidationResult> results) { bool result = true; if (obj != null) { var properties = obj.GetType().GetProperties(); foreach (var property in properties) { object val = property.GetValue(obj, null); if (!property.PropertyType.IsValueType) { result = TryValidatePropertyRecursive(val, results); } else { result = TryValidateProperty(val, obj, results) && result; } } } return result; }
All Replies
-
Tuesday, May 01, 2012 9:36 AM
Hi,
Thanks for your post.
How about your code going? Does it contain some exception?
I have not found the Validator.TryValidateProperty method in the code (in the link), So would you like to share some information about it?
I will suggest you to create your own code instead of using others' code. You need to read the code firstly, try to remeber it, and write the code by yourself insteading of just editing the code. He need the code because he inhert the infterface witch contain two methods. and you can avoid doing that and make your application easier.
Hope this helps.
No code, No fact.
- Edited by calanghei Tuesday, May 01, 2012 9:39 AM
-
Tuesday, May 01, 2012 1:52 PM
the link provided NOT using TryValidateProperty instead it uses TryValidateObject which validates entire object including its properties. I want to validate individual property on my own.
The logic in my code is little different than whats in the link.
One other problem i have is that, TryValidateProperty throws exception when validation fails, unlike TryValidateObject method which puts all the errors in collection and returns bool

