簡體   English   中英

使用 Fluent Validation 如何檢查對象中的兩個屬性都不能有值?

[英]Using Fluent Validation how can I check that two properties in an object both can't have a value?

我想驗證一個類中的兩個屬性( MyProperty1MyProperty2 )。 這些屬性都可以為空。 它們都有單獨的驗證規則,但它們不能都有一個值集。

public MyObject 
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
}

我試圖避免寫這樣的東西

            When(
            c => c.MyProperty1 != null && c.MyProperty2 != null,
            () =>
                this.RuleFor(r => r.MyProperty1 )
                    .Null()
                    .WithMessage("MyProperty1 must be null when MyProperty2 has value"));

以下將實現這一點並保持流暢的可讀性。

RuleFor(o => o.MyProperty1)
    .Null()
    .When(o => o.MyProperty2 != null)
    .WithMessage("MyProperty1 must be null when MyProperty2 has value");

RuleFor(o => o.MyProperty2)
    .Null()
    .When(o => o.MyProperty1 != null)
    .WithMessage("MyProperty2 must be null when MyProperty1 has value");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM