[英]Using Fluent Validation how can I check that two properties in an object both can't have a value?
I want to validate two properties ( MyProperty1
, MyProperty2
) in a class.我想验证一个类中的两个属性(
MyProperty1
、 MyProperty2
)。 These properties can both be null.这些属性都可以为空。 They both have separate validation rules but they cannot both have a value set.
它们都有单独的验证规则,但它们不能都有一个值集。
public MyObject
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
}
I am trying to avoid writing something like this我试图避免写这样的东西
When(
c => c.MyProperty1 != null && c.MyProperty2 != null,
() =>
this.RuleFor(r => r.MyProperty1 )
.Null()
.WithMessage("MyProperty1 must be null when MyProperty2 has value"));
The following will achieve that and keeps the fluent readability.以下将实现这一点并保持流畅的可读性。
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.