Sub topic 11
Using validation groups for create and update
This chapter assumes you can declare constraints on a DTO, trigger them with @Valid, and handle MethodArgumentNotValidException. Earlier chapters cover those.
Why one set of rules is not enough
A create request and an update request often share a DTO but not the same rules. When you create a user, name and email are required. When you update one, the client may send only the fields it wants to change. If you put @NotBlank on every field, partial updates fail. If you remove it, creates accept incomplete data.
You could write two DTOs. That is often the cleanest choice when the shapes differ a lot. When the shapes are the same and only the rules differ, validation groups let you keep one class.
The working model
A validation group is a marker interface. Each constraint lists the groups it belongs to through its groups attribute. When you validate, you name the groups to run. Only constraints that belong to those groups are checked.
A constraint with no groups attribute belongs to the built-in jakarta.validation.groups.Default group.
public interface OnCreate {
}public interface OnUpdate {
}Assigning constraints to groups
The record below requires both fields on create. On update, both are optional, but any value that is sent must still be valid.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record UserRequest(
@NotBlank(groups = OnCreate.class)
@Size(max = 50, groups = {OnCreate.class, OnUpdate.class})
String name,
@NotBlank(groups = OnCreate.class)
@Email(groups = {OnCreate.class, OnUpdate.class})
String email) {
}@Size and @Email treat null as valid. An update that omits name passes, and an update that sends a 60-character name fails.
Selecting a group in the controller
@Valid cannot name a group. Use Spring's @Validated on the parameter instead.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public ResponseEntity<Void> create(
@Validated(OnCreate.class) @RequestBody UserRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@PutMapping("/{id}")
public ResponseEntity<Void> update(
@PathVariable long id,
@Validated(OnUpdate.class) @RequestBody UserRequest request) {
return ResponseEntity.noContent().build();
}
}Failures still raise MethodArgumentNotValidException, so your existing @RestControllerAdvice handler works unchanged.
Common errors
- Constraints silently skipped. Once you name a group, the
Defaultgroup no longer runs. A constraint with nogroupsattribute is ignored on that endpoint. Annotate every constraint you want checked, or make the group extendDefault. - Using
@Validand expecting groups.@Validalways validates theDefaultgroup. Constraints that belong only toOnCreatenever run. - Groups do not cascade by default. A nested
@Validobject is validated with the same group you selected, so its constraints need that group too.
import jakarta.validation.groups.Default;
public interface OnCreate extends Default {
}With this version, @Validated(OnCreate.class) also runs every unannotated constraint. This is convenient for rules that apply everywhere, such as @Size.
Exercise
Exercise
A DTO field is annotated with @NotBlank and no groups attribute. The controller parameter uses @Validated(OnUpdate.class). Is the field checked, and how can you change that?
Show answer
It is not checked, because @NotBlank belongs to the Default group and only OnUpdate runs. Add groups = OnUpdate.class to the constraint, or make OnUpdate extend jakarta.validation.groups.Default.