Advertisement
Lauda

Untitled

Mar 3rd, 2020
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. private static bool TryValidateObjectRecursively(object instance, ICollection<ValidationResult> results, bool validateAllProperties)
  2.         {
  3.             if (instance is null)
  4.                 throw new ArgumentNullException(nameof(instance));
  5.  
  6.             var isValid = true;
  7.             var tempResults = new List<ValidationResult>();
  8.             var context = new ValidationContext(instance);
  9.  
  10.             isValid &= Validator.TryValidateObject(instance, context, tempResults, validateAllProperties);
  11.  
  12.             foreach (var item in tempResults)
  13.             {
  14.                 results.Add(new ValidationResult(item.ErrorMessage, item.MemberNames));
  15.             }
  16.  
  17.             foreach (var prop in instance.GetType().GetProperties())
  18.             {
  19.                 if (prop.GetSetMethod() == null)
  20.                     continue;
  21.  
  22.                 if (!prop.PropertyType.IsClass || prop.PropertyType == typeof(string))
  23.                     continue;
  24.  
  25.                 var value = prop.GetValue(instance);
  26.                 switch (value)
  27.                 {
  28.                     case null:
  29.                         continue;
  30.                     case IEnumerable<object> list:
  31.                         {
  32.                             isValid = list.Aggregate(isValid, (current, item) => current & TryValidateObjectRecursively(item, results, validateAllProperties));
  33.                             break;
  34.                         }
  35.                     default:
  36.                         {
  37.                             isValid &= TryValidateObjectRecursively(value, results, validateAllProperties);
  38.                             break;
  39.                         }
  40.                 }
  41.             }
  42.  
  43.             return isValid;
  44.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement