Spring Rest Controller: how to selectively disable validation

In my controller, I have an object creation method

import javax.validation.Valid; ... @RestController public class Controller { @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> create(@Valid @RequestBody RequestDTO requestDTO) { ... 

with

 import org.hibernate.validator.constraints.NotEmpty; ... public class RequestDTO @NotEmpty // (1) private String field1; //other fields, getters and setters. 

I want to add a controller method

 update(@Valid @RequestBody RequestDTO requestDTO) 

but in this method, it must be acceptable for field1 be empty or zero, i.e. line

 @NotEmpty // (1) 

RequestDTO should be ignored.

How can i do this? Should I write a class that looks exactly like RequestDTO but does not contain annotations? Or is this possible through inheritance?

+5
source share
1 answer

Short answer: use validation groups:

 @NotEmpty(groups = SomeCriteria.class) private String field1; 

And refer to your intended group in the parameters of the method handler:

 public ResponseEntity<?> create(@Validated(SomeCriteria.class) @RequestBody RequestDTO requestDTO) 

In the above example, the checks in the SomeCriteria group will be applied, while others will be ignored. Typically, these verification groups are defined as empty interfaces:

 public interface SomeCriteria {} 

You can learn more about these group restrictions in the Hibernate validator documentation .

+8
source

Source: https://habr.com/ru/post/1244132/


All Articles