DEV Community

Cover image for Spring Boot Validation Groups
Dave Brown
Dave Brown

Posted on

Spring Boot Validation Groups

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;
}
Enter fullscreen mode Exit fullscreen mode

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) { ... }
Enter fullscreen mode Exit fullscreen mode

Spring applies only the constraints matching the group you specify. Constraints with no group annotation apply in both cases.

This scales well for lifecycle-based rules — fields that are optional on creation but locked down once a record is active, or validation that only applies during specific operations.

Full article covers this plus custom field-level validators, class-level multi-field constraints, and service-layer validation: https://tucanoo.com/spring-boot-input-validation-complete-guide/

SpringBoot #Java #APIDesign

Top comments (0)