Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 756
Happy Avatar asked Jan 27 '17 21:01

Happy


People also ask

How do you pass a request body in REST API Spring boot?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.


1 Answers

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.

like image 86
Ken Bekov Avatar answered Oct 18 '22 10:10

Ken Bekov