Reputation: 1456
I want to validate two properties (MyProperty1
, MyProperty2
) in a class. 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"));
Upvotes: 4
Views: 2846
Reputation: 2039
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");
Upvotes: 3