Back to articles
Spring Boot Validation Groups

Spring Boot Validation Groups

via Dev.to WebdevDave Brown

If you've ever written nearly-identical CreateRequest and UpdateRequest DTOs just because the validation rules differ (ID must be null on create, required on update), there's a better way. Spring Boot's Validation Groups let you define different constraint profiles on a single DTO and activate the right one per endpoint. The setup: public interface OnCreate {} public interface OnUpdate {} public class UserRequest { @Null ( groups = OnCreate . class ) @NotNull ( groups = OnUpdate . class ) private Long id ; @NotBlank private String name ; } In your controller, swap @valid for @Validated with the group: @PostMapping public ResponseEntity <?> create ( @Validated ( OnCreate . class ) @RequestBody UserRequest req ) { ... } @PutMapping ( "/{id}" ) public ResponseEntity <?> update ( @Validated ( OnUpdate . class ) @RequestBody UserRequest req ) { ... } Spring applies only the constraints matching the group you specify. Constraints with no group annotation apply in both cases. This scales well

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
2 views

Related Articles