2014-08-29 206 views
3

在为Fluent验证规则构建器编写扩展时,我提出了进行更复杂的验证并将其与客户端验证连接起来的想法。我已经成功创建了基于另一个属性验证一个属性的扩展,等等。我所挣扎的是在多个领域的验证:复杂验证扩展

扩展方法作为https://fluentvalidation.codeplex.com/wikipage?title=Custom&referringTitle=Documentation

public static IRuleBuilderOptions<T, TProperty> Required<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Action<MyRuleBuilder<T>> configurator) 
    { 
     MyRuleBuilder<T> builder = new MyRuleBuilder<T>(); 

     configurator(builder); 

     return ruleBuilder.SetValidator(new MyValidator<T>(builder)); 
    } 

的MyRuleBuilder类允许添加规则流利:

public class MyRuleBuilder<T> 
{ 
    public Dictionary<string, object> Rules = new Dictionary<string,object>(); 

    public MyRuleBuilder<T> If(Expression<Func<T, object>> exp, object value) 
    { 
     Rules.Add(exp.GetMember().Name, value); 

     return this; 
    } 
} 

然后视图模型和查看模型验证器规则如下所示:

public class TestViewModel 
{ 
    public bool DeviceReadAccess { get; set; } 
    public string DeviceReadWriteAccess { get; set; } 
    public int DeviceEncrypted { get ; set; } 
} 

RuleFor(x => x.HasAgreedToTerms) 
    .Required(builder => builder 
     .If(x => x.DeviceReadAccess, true) 
     .If(x => x.DeviceReadWriteAccess, "yes") 
     .If(x => x.DeviceEncrypted, 1)); 

问题:

上述工作正常,但我不喜欢的是“If”功能。它不会强制所选属性类型的值。例如:

RuleFor(x => x.HasAgreedToTerms) 
    .Required(builder => builder 
     .If(x => x.DeviceReadAccess, true) // I would like the value to be enforced to bool 
     .If(x => x.DeviceReadWriteAccess, "yes") // I would like the value to be enforced to string 

// Ideally something like 

// public MyRuleBuilder<T> If(Expression<Func<T, U>> exp, U value) but unfortunately U cannot be automatically inferred 

这是可能的这种架构或我应采取不同的方法?

谢谢。

回答

0

我认为你可以添加另一个通用参数U的方法。

public class MyRuleBuilder<T> 
{ 
    public Dictionary<string, object> Rules = new Dictionary<string, object>(); 

    public MyRuleBuilder<T> If<U>(Expression<Func<T, U>> exp, U value) 
    { 
     Rules.Add(exp.GetMember().Name, value); 

     return this; 
    } 
} 
+0

在这种情况下,T将是TestViewModel类型和U会是什么类型?请记住,在必需的扩展功能中有一个Action委托,它具有MyRuleBuilder 。你在这里通过什么? – Zanuff 2014-08-29 11:58:36

+0

@Zanuff你是对的...你必须添加另一个通用参数到接口以及...参数将改变你将不得不通过'Action ',我不确定你是否可以做到这一点... – dburner 2014-08-29 13:03:24

+0

@Zanuff我没有意识到我没有添加通用参数的方法....检查我的编辑。 – dburner 2014-08-29 13:57:37