Stop Fluent Validation on first failure

前端 未结 3 408
暖寄归人
暖寄归人 2021-02-04 02:12

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

3条回答
  •  野性不改
    2021-02-04 03:14

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

提交回复
热议问题