Stop Fluent Validation on first failure

前端 未结 3 410
暖寄归人
暖寄归人 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:12

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

提交回复
热议问题