Validation with Annotations
Validation checks a request body before the app saves it. The @Valid annotation switches the checks on.
A rule on the title field
@Size sets the shortest and longest allowed text.
public record TaskForm(
@Size(min = 3, max = 100) String title,
boolean done) {
}Mark the body for checks
@Valid on the body value switches the checks on.
@Valid @RequestBody TaskForm formExample
package com.example.demo;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskRepository repository;
public TaskController(TaskRepository repository) {
this.repository = repository;
}
@PostMapping("/tasks")
public ResponseEntity<TaskView> createTask(@Valid @RequestBody TaskForm form) {
Task task = new Task(form.title(), form.done());
repository.save(task);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new TaskView(task.getTitle(), task.isDone()));
}
public record TaskForm(
@Size(min = 3, max = 100) String title,
boolean done) {
}
public record TaskView(String title, boolean done) {
}
}Key points
- @Valid sits on the request body value.
- Annotations on the fields state the rules.
- An annotation is a marker above a field.
- @Size sets the shortest and longest allowed text.
- A bad body is rejected with status 400.
- A good body passes through to the method.
- Validation runs before the method body runs.
In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The TaskForm record carries the rule, so a title must be 3 to 100 letters long. The createTask method marks the body with @Valid, so Spring checks it first. A good title is saved and answered with 201. A title of two letters is rejected with 400.
Note
The rules live on a form record, not on the entity.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @Valid do?