Stop Fluent Validation on first failure

蓝咒 提交于 2019-12-02 22:52:14

Just check for null before running the rules that depend on them, using a When condition.

this.CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.TechnicalHeader).NotNull().WithMessage("Header cannot be null");

// Ensure TechnicalHeader is provided
When(x => x.TechnicalHeader != null, () => {
    RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
    RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
    RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
});
Francis Shaw

Just add SetValidator before running the rules that depend on them, using a Custom condition:

//if InpatOrderImportValidatorBllNode fail ,the custom method cannot be executed
RuleFor(x => x).Cascade(CascadeMode.StopOnFirstFailure)
               .SetValidator(new InpatOrderImportValidatorBllNode())
               .Custom((input, context) => {          
                  context.AddFailure(new ValidationFailure("DrugTypeName", "fail"));
               });

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<T, TProperty> DependentRules<T, TProperty>(
        this IRuleBuilderOptions<T, TProperty> currentRule, 
        Action<IRuleBuilderOptions<T, TProperty>> action)
    {
        return currentRule.DependentRules(() => action(currentRule));
    }

So the definitve code:

RuleFor(object => object.String)
    .NotNull()
    .DependentRules(currentRule =>
    {
        currentRule
            .NotEmpty()
            .Matches("^[A-Z]{3}$");
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!