Skip to content

Instantly share code, notes, and snippets.

@dontpaniclabsgists
Created April 16, 2024 18:35
Show Gist options
  • Save dontpaniclabsgists/d4a8aa6f5da8f77964da68b71f6f7ed2 to your computer and use it in GitHub Desktop.
Save dontpaniclabsgists/d4a8aa6f5da8f77964da68b71f6f7ed2 to your computer and use it in GitHub Desktop.
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