使用FluentValidation库自动对属性进行验证过程

时间:2016-03-22 06:17:08

标签: c# .net fluentvalidation

想知道是否有可能避免为需要验证的每个字段编写规则,例如,除了Remarks之外,必须验证所有属性。我正在考虑避免为每个属性写RuleFor

public class CustomerDto
{
    public int CustomerId { get; set; }         //mandatory
    public string CustomerName { get; set; }    //mandatory
    public DateTime DateOfBirth { get; set; }   //mandatory
    public decimal Salary { get; set; }         //mandatory
    public string Remarks { get; set; }         //optional 
}

public class CustomerValidator : AbstractValidator<CustomerDto>
{
    public CustomerValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.CustomerName).NotEmpty();
        RuleFor(x => x.DateOfBirth).NotEmpty();
        RuleFor(x => x.Salary).NotEmpty();
    }
}

1 个答案:

答案 0 :(得分:0)

你走了:

public class Validator<T> : AbstractValidator<T>
{
    public Validator(Func<PropertyInfo, bool> filter) {
        foreach (var propertyInfo in typeof(T)
            .GetProperties()
            .Where(filter)) {
            var expression = CreateExpression(propertyInfo);
            RuleFor(expression).NotEmpty();
        }
    }

    private Expression<Func<T, object>> CreateExpression(PropertyInfo propertyInfo) {
        var parameter = Expression.Parameter(typeof(T), "x");
        var property = Expression.Property(parameter, propertyInfo);
        var conversion = Expression.Convert(property, typeof(object));
        var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter);

        return lambda;
    }
}

它可以这样使用:

    private static void ConfigAndTestFluent()
    {
        CustomerDto customer = new CustomerDto();
        Validator<CustomerDto> validator = new Validator<CustomerDto>(x=>x.Name!="Remarks"); //we specify here the matching filter for properties
        ValidationResult results = validator.Validate(customer);
    }