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

1 answer

  • answered 2020-03-31 11:26 colinD

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