Johannes Klug
Johannes Klug

Reputation: 1115

Spring boot: @Valid not working with @RequestHeader

I'm really struggling to combine @Valid with @RequestHeader. Might this be not supported or is there a way to enable it? I couldn't find useful information about that...

When I annotate the whole controller with @Validated it works, so it is not a big issue. However, I feel like it should work with @Valid as well, so I wanted to know if I'm missing something here.

Code example:

    @GetMapping("/validationControllerHeader")
    public String validationControllerHeader(@Valid @RequestHeader @Pattern(regexp = "[a-z]{3}[0-9]+") String someheader) {
        return someheader;
    }

I'm using @Valid in the same test controller for query parameters and body validation too and there it works, so the issue is only present with headers.

Using spring boot 2.3.1.RELEASE

Upvotes: 1

Views: 1897

Answers (1)

cassiomolin
cassiomolin

Reputation: 131017

You are definitely supposed to use @Validated in your controller class, as it indicates that the validation is meant to be performed in that class. From the documentation:

To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation, which can optionally also declare the validation groups to use.

And, as you are using @Pattern (which is a Bean Validation annotation), you don't need @Valid.

Upvotes: 3

Related Questions