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
這是可能的這種架構或我應採取不同的方法?
謝謝。
在這種情況下,T將是TestViewModel類型和U會是什麼類型?請記住,在必需的擴展功能中有一個Action委託,它具有MyRuleBuilder。你在這裏通過什麼? –
Zanuff
2014-08-29 11:58:36
@Zanuff你是對的...你必須添加另一個通用參數到接口以及...參數將改變你將不得不通過'Action',我不確定你是否可以做到這一點... –
dburner
2014-08-29 13:03:24
@Zanuff我沒有意識到我沒有添加通用參數的方法....檢查我的編輯。 – dburner 2014-08-29 13:57:37