Spring Boot Validation Groups Simplify DTO Validation

The classic Spring Boot validation trap: you have a User DTO. On create, id must be null. On update, id must be present. So you either duplicate the DTO or add conditional checks that progressively make the codebase harder to read. Validation Groups solve this cleanly. You define interface markers — OnCreate and OnUpdate — then annotate constraints with the appropriate group. @Null(groups = OnCreate.class) on id for creates. @NotNull(groups = OnUpdate.class) on id for updates. Same DTO, entirely different validation behaviour depending on which group you pass via Validated in the controller. The javax.validation spec has supported this for years, but it doesn't get discussed enough. Teams discover it after the fact, usually after spending two sprints maintaining parallel DTO hierarchies that drift out of sync. A few things worth knowing: • Default constraints (no group specified) only run when no groups are passed. Once you start using groups, be explicit everywhere. • Spring's Validated is what enables group selection — Valid doesn't support groups. • Validation Groups compose — you can pass multiple groups when needed. We've written a complete guide on Spring Boot input validation covering groups, custom validators, controller-level wiring, and the common mistakes teams make. 👉 https://lnkd.in/eypuK5b9 #SpringBoot #Java #SoftwareDevelopment #CleanCode #APIDesign

  • The classic Spring Boot validation trap: you have a User DTO. On create, id must be null. On update, id must be present. So you either duplicate the DTO or add conditional checks that progressively make the codebase harder to read.

Validation Groups solve this cleanly.

You define interface markers — OnCreate and OnUpdate — then annotate constraints with the appropriate group. @Null(groups = OnCreate.class) on id for creates. @NotNull(groups = OnUpdate.class) on id for updates. Same DTO, entirely different validation behaviour depending on which group you pass via @Validated in the controller.

The javax.validation spec has supported this for years, but it doesn't get discussed enough. Teams discover it after the fact, usually after spending two sprints maintaining parallel DTO hierarchies that drift out of sync.

A few things worth knowing:
• Default constraints (no group specified) only run when no groups are passed. Once you start using groups, be explicit everywhere.
• Spring's @Validated is what enables group selection — @Valid doesn't support groups.
• Validation Groups compose — you can pass multiple groups when needed.

We've written a complete guide on Spring Boot input validation covering groups, custom validators, controller-level wiring, and the common mistakes teams make.

👉 https://tucanoo.com/spring-boot-input-validation-complete-guide/

#SpringBoot #Java #SoftwareDevelopment #CleanCode #APIDesign

To view or add a comment, sign in

Explore content categories