Created
April 16, 2024 18:35
-
-
Save dontpaniclabsgists/d4a8aa6f5da8f77964da68b71f6f7ed2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private bool ValidateObject(object obj, string[] allowedNulls = null) | |
{ | |
if (obj == null) | |
{ | |
return false; | |
} | |
foreach (PropertyInfo property in obj.GetType().GetProperties()) | |
{ | |
if (property.GetIndexParameters().Length > 0) | |
{ | |
// This property is an indexer and we cannot validate it | |
continue; | |
} | |
var value = property.GetValue(obj); | |
var canProptertyBeNull = !(allowedNulls == null) || (allowedNulls != null && allowedNulls.Contains(property.Name)); | |
if (value == null && !canProptertyBeNull) | |
{ | |
return false; | |
} | |
if (property.PropertyType.IsClass && property.PropertyType != typeof(string)) | |
{ | |
if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) | |
{ | |
// The property is a collection | |
var enumerable = (IEnumerable)value; | |
foreach (var item in enumerable) | |
{ | |
if (!ValidateObject(item)) | |
{ | |
return false; | |
} | |
} | |
} | |
else | |
{ | |
// The property is a class | |
if (!ValidateObject(value)) | |
{ | |
return false; | |
} | |
} | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment