2016-03-22 8 views
0

検証する必要があるすべてのフィールドに対してルールを書くことを避けることができます。例としては、Remarks以外のすべてのプロパティを検証する必要があります。そして私はすべての不動産についてRuleForと書くことを避けることを考えていました。FluentValidationライブラリを使用してプロパティの検証プロセスを自動化

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

そして、それをそのまま使用することができます:ここで

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

確か – Domysee

+0

どのくらいの頻度ですべてのプロパティに同じ検証パターンがありますか? – Dennis

+0

@Domysee、例を共有していただけますか? –

答えて

0

あなたは行く良いスタートとすることができる反射および/または属性を使用して、次のことができ

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); 
    } 
関連する問題