我有一个具有某些属性的 Person 类,因此我想默认情况下自动对所有属性应用 FluentValidation 规则
- Example:
string: NotNull(), NotEmpty(), Length()...
enum: IsInEnum()
List: NotNull() or something else...
- ...
人与扩展方法
public enum Gender { Male, Female }
public class Person
{
public Gender Gender { get; set; }
public string Name { get; set; }
public List<string> Notes { get; set; }
}
public static class Extension
{
public static Expression<Func<T, TProperty>> GenerateExpression<T, TProperty>(PropertyInfo propInfo)
{
ParameterExpression paramExp = Expression.Parameter(typeof(T));
MemberExpression memExp = Expression.Property(paramExp, propInfo);
UnaryExpression unaryExp = Expression.Convert(memExp, propInfo.PropertyType);
return Expression.Lambda<Func<T, TProperty>>(unaryExp, paramExp);
}
}
基础验证器
I use Extension.GenerateExpression
建造Expression
基于列表属性,然后将其传递到RuleFor()
,但它仅适用于字符串类型。
我不知道如何处理其他数据类型。
public class BaseValidator<T> : AbstractValidator<T>
{
public BaseValidator()
{
ParameterExpression paramExp = Expression.Parameter(typeof(T));
foreach (PropertyInfo propInfo in typeof(T).GetProperties())
{
// String [WORKED]
if (propInfo.PropertyType == typeof(string))
{
Expression<Func<T, string>> expression = Extension.GenerateExpression<T, string>(propInfo);
RuleFor(expression).Length(1, 10); //.Matches("pattern");
}
// List [NOT WORK]
else if (propInfo.PropertyType.IsGenericType)
{
Expression<Func<T, object>> expression = Extension.GenerateExpression<T, object>(propInfo);
RuleFor(expression).NotNull(); //ItemsInRange(1, 2);
}
// Enum [EXCEPTION]
else if (propInfo.PropertyType.IsEnum)
{
Expression<Func<T, Enum>> expression = Extension.GenerateExpression<T, Enum>(propInfo);
// Expression of type 'Gender' cannot be used for return type 'System.Enum''
RuleFor(expression).IsInEnum();
}
// Other type [How to handle?]
else
{
//Expression<Func<T, ???>> expression = GenerateExpression<T, ???>(propInfo);
}
}
}
}
人员验证器
public class PersonValidator : BaseValidator<Person> { }
Program
public class Program
{
public static void Main(string[] args)
{
Person person = new Person
{
Name = "Name",
Gender = Gender.Male,
Notes = new List<string> { "Note 1", "Note 2" }
};
PersonValidator validation = new PersonValidator();
ValidationResult result = validation.Validate(person);
foreach (var error in result.Errors)
{
Console.WriteLine(error);
}
Console.ReadKey();
}
}