I have a Spring Boot Controller with POST and PUT method's and a custom validator.
@Autowired
PersonValidator validator;
@InitBinder
protected void initBinder(final WebDataBinder binder) {
binder.addValidators(validator);
}
@PostMapping
public ResponseEntity<String> save(@Valid @RequestBody Person person) {}
@PutMapping
public ResponseEntity<String> update(@Valid @RequestBody Person person) {}
Currently both POST and PUT methods are using the same validation rules. QUESTION: I would need to have different validation rules for PUT and POST. Any ideas on how to proceed, how can I use different custom validators within the same RestController?
You can integrate Hibernate Validator in your application if you are using Spring boot. It seems that you need to implement Grouping constraints (https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-groups)
e.g.
Entity
@NotEmpty(groups = PutValidation.class)
private String field1;
@Size(min = 3, groups = PutValidation.class)
@Size(min = 5, groups = PostValidation.class)
private String field2;
@Min(value = 18, groups = {PostValidation.class,PutValidation.class,Default.class})
private int age;
//Getters/setters
Groups (these are nothing but empty interfaces)
public interface PostValidation {
}
public interface PutValidation {
}
How to use group of constraints in Controller
@PostMapping
public ResponseEntity<String> save(@Validated(PostValidation.class) @RequestBody Person person) {}
@PutMapping
public ResponseEntity<String> update(@Validated(PutValidation.class) @RequestBody Person person) {}
I hope this can help to solve your problem.
Cheers!
You could create your own annotations for each Validator and replace @Valid at each endpoint. Have a look at @InRange: https://lmonkiewicz.com/programming/get-noticed-2017/spring-boot-rest-request-validation/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With