【问题标题】:Automate the validation process on properties using FluentValidation Library使用 FluentValidation 库自动化属性验证过程
【发布时间】:2016-03-22 06:17:07
【问题描述】:

想知道是否有可能避免为需要验证的每个字段编写规则,例如,除了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();
    }
}

【问题讨论】:

  • 当然可以,使用反射和/或属性可能是一个好的开始
  • 所有属性的验证模式相同的频率如何?
  • @Domysee,你能分享一个例子吗?
  • @Dennis:我经常开始注意到系统中其他类的相同验证模式。所以,我想把这些东西自动化..

标签: c# .net fluentvalidation


【解决方案1】:

给你:

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);
    }

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多