i\'m defining a validation for my Request objects. I would like the validator to stop on the very first failure, not only the one on the same chain. In the example below, if my
You can use DependentRules.
RuleFor(object => object.String)
.NotNull()
.DependentRules(() =>
{
RuleFor(object => object.String)
.NotEmpty()
.Matches("^[A-Z]{3}$");
});
Then you dont duplicate validation code.
You can even add an extension method for no duplicating the RuleFor.
public static IRuleBuilderOptions DependentRules(
this IRuleBuilderOptions currentRule,
Action> action)
{
return currentRule.DependentRules(() => action(currentRule));
}
So the definitve code:
RuleFor(object => object.String)
.NotNull()
.DependentRules(currentRule =>
{
currentRule
.NotEmpty()
.Matches("^[A-Z]{3}$");
});