Happy
Happy

Reputation: 1865

Spring REST how to validate request body in different ways?

With @Valid we can parse the request body and validate it with annotations like @NotEmpty, @Size(min = 5). Is there a way to have multiples ways to validate the body? For example, on some endpoints, I would like to ignore some validators (@NotNull in my case).

My guess was to create a custom annotation like @ValidUnlessNull, but how can I implement its resolver without having to do the job of @RequestBody (I tried to implement a Filter and a HandlerMethodArgumentResolver)?

Upvotes: 5

Views: 13364

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

You can define custom validation groups and select any group with @Validated annotation.

1) Define empty interface, that will be used as validation group identifier:

public interface FirstValidateGroup{}

2) Bind validation annotation to specified interface (group):

public class Person{

    @NotBlank(groups = {FirstValidateGroup.class})
    private String firstName;
    @NotBlank
    private String lastName;

    //... getters and setters
}

Note, that you can bind multiple groups for one property.

3) Select group of validation with @Validated annotation:

public ResponseEntity<Person> add(@Validated({FirstValidateGroup.class}) 
                                  @RequestBody Person person){
   ...
}

Now, only firstName property will be validated. You can specify multiple groups in @Validated annotation.

Upvotes: 9

Alexander.Furer
Alexander.Furer

Reputation: 1869

Validation group is your friend. You just need to provide appropriate group per endpoint. See my comment here Spring MVC @Valid Validation with custom HandlerMethodArgumentResolver to invoke validation with group hint.

Upvotes: 0

Related Questions