Skip to content

Instantly share code, notes, and snippets.

@DalSoft
Created July 1, 2022 11:51
Show Gist options
  • Save DalSoft/a103886152e8b8b9d16d035f064ba825 to your computer and use it in GitHub Desktop.
Save DalSoft/a103886152e8b8b9d16d035f064ba825 to your computer and use it in GitHub Desktop.
Validate Empty using C# expressions
// 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