Skip to content

Instantly share code, notes, and snippets.

@MichaelaIvanova
Created April 5, 2019 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelaIvanova/0bad20fbf6c35d05bc7a472fc2473c60 to your computer and use it in GitHub Desktop.
Save MichaelaIvanova/0bad20fbf6c35d05bc7a472fc2473c60 to your computer and use it in GitHub Desktop.
C# Model Required field attribute
public class ValidationHelper : IValidationHelper
{
public bool AllPropertiesAreValid(object obj)
{
if (obj == null)
{
return false;
}
return obj.GetType().GetProperties().All(p =>
{
var attrib = p.GetCustomAttributes(typeof(ValueRequiredAttribute), true)
.FirstOrDefault() as ValueRequiredAttribute ?? new ValueRequiredAttribute();
return attrib.Validate(p.GetValue(obj));
});
}
}
[AttributeUsage(AttributeTargets.Property)]
public class ValueRequiredAttribute : Attribute
{
public bool Validate<T>(T value)
{
if (Equals(value, default(T)))
{
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment