2011-07-28 31 views
1

我有Fluent驗證問題。錯誤消息不在FLuentValidation中顯示爲可空類型

我想檢查驗證,所以屬性必須填充大於其他屬性。 這裏是代碼:

public decimal? MonthlySalesNet { get; set; } 
public decimal? MonthlySalesGross { get; set; } 

,這裏是驗證:

RuleFor(x => x.MonthlySalesGross.Value).GreaterThan(x => x.MonthlySalesNet.Value) 
      .When(x => x.MonthlySalesGross != null && x.MonthlySalesNet != null) 
      .WithMessage("blahblah"); 

驗證是工作,但沒有顯示的消息。我錯過了什麼嗎?

當我將十進制更改爲不可爲空類型並重新配置驗證時,會顯示錯誤消息驗證。它了怪異的我,,謝謝

+0

我在codeplex的流暢驗證論壇上交叉發佈。 這裏是答案:http://fluentvalidation.codeplex.com/discussions/266845 – Rivera

回答

2

(我張貼了同樣的答案在上FV forum

消息不顯示,因爲它認爲它與錯誤的屬性相關聯。當您使用RuleFor(x => x.MonthlySalesGross.Value)時,它將該規則與名爲「Value」的屬性相關聯,而不是與MonthlySalesGross屬性相關聯。

FluentValidation v3增加了對可空數據的更好支持(我在這篇博客上發表了博文here),但是目前這隻適用於常量值,而不是引用其他屬性的表達式。我計劃擴展可空支持以與v3.1的跨屬性驗證器一起工作,但現在您可以通過手動覆蓋屬性名稱來解決此問題。這將錯誤與正確的屬性重新關聯:

RuleFor(x => x.MonthlySalesGross.Value) 
    .GreaterThan(x => x.MonthlySalesNet.Value) 
    .When(x => x.MonthlySalesGross.HasValue) 
    .OverridePropertyName("MonthlySalesGross"); 

(請注意,您還必須包括一個條款時一個空檢查)。