Created
July 1, 2022 11:51
-
-
Save DalSoft/a103886152e8b8b9d16d035f064ba825 to your computer and use it in GitHub Desktop.
Validate Empty using C# expressions
This file contains 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
// Usage ValidateEmpty(x => x.Id), | |
public static ValidationResult ValidateEmpty<T, TProp>(this T o, Expression<Func<T,TProp>> propertySelector) | |
{ | |
MemberExpression body = (MemberExpression)propertySelector.Body; | |
var propInfo = body.Member as PropertyInfo; | |
var value = propInfo?.GetValue(o, null); | |
return value switch | |
{ | |
null => new ValidationResult($"{body.Member.Name} is required", new[] {body.Member.Name}), | |
string s => string.IsNullOrWhiteSpace(s) | |
? new ValidationResult($"{body.Member.Name} is required", new[] {body.Member.Name}) | |
: ValidationResult.Success, | |
ICollection c => c.Count == 0 | |
? new ValidationResult($"{body.Member.Name} is required", new[] {body.Member.Name}) | |
: ValidationResult.Success, | |
_ => ValidationResult.Success | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment