Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot REST controller: different custom validators for POST and PUT methods receiving the same object

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?

like image 278
Kari Sarsila Avatar asked Dec 02 '25 14:12

Kari Sarsila


2 Answers

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!

like image 86
Karl Avatar answered Dec 05 '25 04:12

Karl


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/

like image 40
DCO Avatar answered Dec 05 '25 05:12

DCO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!