spring-mvcjava-21jakarta-validation

Jakarta's validation group triggers despite previous group failing


I use a Spring MVC controller to call an endpoint expecting this DTO:

@GroupSequence({ Dto.class, ExistingEntity.class })
public record Dto(
    @Valid
    @NotEmpty
    @ExistingAccesses(groups = ExistingEntity.class)
    List<@Valid Access> accesses
) {
    public record Access(
        @NotNull
        Long id,

        @NotEmpty
        List<String> roles
    ) {}
}

In the custom validator, I use the values of id and roles fields without null checks. Sending a payload with one of these fields missing throws an NPE in the custom validator.

I know that the @NotNull and @NotEmpty validations do trigger, because they reject the payload with the proper error if I remove the @ExistingAccesses custom validation.

So, it seems that the second validation group is triggering despite the default one failing. I don't know why or how to fix it.

I've tried using another custom validation group instead of the default, and converting these records to classes, which did nothing.


Solution

  • Short answer if by default you use HibernateValidator (what comes as default in spring mvc), then you need redefine Validator bean with property "failFast" set.

    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
    

    usefull link: https://mossgreen.github.io/Validations-in-Spring/

    PS In terms of usability it's always better to know all needed fields rather than hit API and learn that you miss another field. So it can be useful only if your validation is complex or consume lot of time.