I have a FluentValidator that has multiple properties like zip and county etc. I want to create a rule that takes two properties just like a RuleFor construct
In my case I needed to mark a property as required (x.RequiredProperty
in the example below) if another property was not null (x.ParentProperty
in the example below). I ended up using the When
syntax:
RuleFor(x => x.RequiredProperty).NotEmpty().When(x => x.ParentProperty != null);
Or if you have more then one rule for a common when clause you can write it as follows:
When(x => x.ParentProperty != null, () =>
{
RuleFor(x => x.RequiredProperty).NotEmpty();
RuleFor(x => x.OtherRequiredProperty).NotEmpty();
});
The definition of the When
syntax is the following:
///
/// Defines a condition that applies to several rules
///
/// The condition that should apply to multiple rules
/// Action that encapsulates the rules.
///
public IConditionBuilder When (Func predicate, Action action);