使用 Fluent 验证如何检查对象中的两个属性是否都不能具有值?



我想验证一个类中的两个属性(MyProperty1MyProperty2(。这两个属性都可以为null。它们都有单独的验证规则,但不能都有一个值集。

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");

最新更新