[英]Is there a way to completely ignore a property using FluentValidation?
[英]How to make FluentValidation ignore a property
我有以下視圖模型
public class MyViewModel
{
public MyViewModelClassWithValidator MandatoryProperty {get; set;}
public MyViewModelClassWithValidator OptionalProperty {get; set;}
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x=> x.MandatoryProperty) //...
//No rule for property 2
}
}
}
我正在尋找一種使FluentValidation忽略OptionalProperty的方法。 在這里,Optional Property的驗證錯誤仍然會添加到ModelState中。
這個答案建議要么1.避免重用子模型,但這不是我的選擇,並且2.從ModelState中刪除錯誤。 在編寫一個骯臟的類以從HttpContext獲取ModelState之前,我想知道是否還有另一種我不知道的方法,因為答案很舊。
我的目標是將驗證邏輯封裝在ViewModels中。
謝謝
好的,所以我找到了一個簡單的解決方法。 我用ThreadStatic字段創建了一個擴展類,其中包含對當前控制器的引用。 我所有的控制器都派生自基本控制器,因此我只需在構造函數中設置當前控制器即可。 一旦有了控制器,我還將擁有ModelState,從而解決了問題。
您可以嘗試這樣的事情:
actual.ShouldBeEquivalentTo(expected, config=> config.Excluding(s => s.TimeStamp), "because they should be similar");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.