Created
April 5, 2019 11:59
-
-
Save MichaelaIvanova/0bad20fbf6c35d05bc7a472fc2473c60 to your computer and use it in GitHub Desktop.
C# Model Required field attribute
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
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