TExcelTAD
Home › Spring Boot › Validation

Validation

Never trust input. A title may be empty, a due date in the past, an email malformed. Instead of writing if statements in every controller, Spring Boot uses Jakarta Bean Validation (implemented by Hibernate Validator): you put constraint annotations on your DTOs and add @Valid where the object enters your application.

Add the starter first — it is not part of spring-boot-starter-web:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Constraints on a record

java
import jakarta.validation.constraints.*;

public record NewTask(
        @NotBlank @Size(max = 120) String title,
        @Size(max = 2000) String description,
        @NotNull Priority priority,
        @FutureOrPresent LocalDate dueDate,
        @Min(0) @Max(100) Integer estimateHours,
        @Email String assigneeEmail) {}
java
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Task create(@Valid @RequestBody NewTask body) {       // @Valid triggers validation
    return service.create(body);
}

If any constraint fails, Spring throws MethodArgumentNotValidException before your method runs and the client gets 400 Bad Request.

Common constraints

Annotation Checks null is
@NotNull value is not null invalid
@NotEmpty not null and length/size > 0 invalid
@NotBlank not null and contains a non-whitespace char invalid
@Size(min, max) string length or collection size valid
@Min / @Max numeric bounds valid
@Positive / @PositiveOrZero sign valid
@Email email format valid
@Pattern(regexp) matches a regex valid
@Past / @Future / @FutureOrPresent dates valid

Note the last column: most constraints treat null as valid, so combine them with @NotNull / @NotBlank when a field is required.

What a validator does

The validator inspects each field, applies each constraint and collects all violations (it does not stop at the first). This plain-Java version implements a few rules for the record above:

java · try it yourself
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

enum Priority { LOW, MEDIUM, HIGH }

record NewTask(String title, Priority priority, LocalDate dueDate, Integer estimateHours, String assigneeEmail) {}

record Violation(String field, String message) {}

class TaskValidator {
    private final LocalDate today;
    TaskValidator(LocalDate today) { this.today = today; }

    List<Violation> validate(NewTask t) {
        List<Violation> v = new ArrayList<>();
        if (t.title() == null || t.title().isBlank()) v.add(new Violation("title", "must not be blank"));
        else if (t.title().length() > 120) v.add(new Violation("title", "size must be between 0 and 120"));
        if (t.priority() == null) v.add(new Violation("priority", "must not be null"));
        if (t.dueDate() != null && t.dueDate().isBefore(today))
            v.add(new Violation("dueDate", "must be a date in the present or in the future"));
        if (t.estimateHours() != null && t.estimateHours() < 0)
            v.add(new Violation("estimateHours", "must be greater than or equal to 0"));
        if (t.estimateHours() != null && t.estimateHours() > 100)
            v.add(new Violation("estimateHours", "must be less than or equal to 100"));
        if (t.assigneeEmail() != null && !t.assigneeEmail().matches("[^@\\s]+@[^@\\s]+"))
            v.add(new Violation("assigneeEmail", "must be a well-formed email address"));
        return v;
    }
}

class Main {
    public static void main(String[] args) {
        TaskValidator validator = new TaskValidator(LocalDate.of(2025, 10, 16));

        NewTask good = new NewTask("Plan sprint", Priority.HIGH, LocalDate.of(2025, 11, 3), 4, "an@example.com");
        NewTask bad = new NewTask("  ", null, LocalDate.of(2025, 1, 1), 250, "not-an-email");

        System.out.println("good -> " + validator.validate(good));
        System.out.println("bad  -> 400 Bad Request");
        for (Violation v : validator.validate(bad)) {
            System.out.println("  " + v.field() + ": " + v.message());
        }
    }
}
good -> []
bad  -> 400 Bad Request
  title: must not be blank
  priority: must not be null
  dueDate: must be a date in the present or in the future
  estimateHours: must be less than or equal to 100
  assigneeEmail: must be a well-formed email address

The messages above are the default English messages of Hibernate Validator, so the simulation matches what a real Spring application reports.

The default error response

Out of the box the 400 response does not list which fields failed. Turn on RFC 9457 problem details:

properties
spring.mvc.problemdetails.enabled=true
bash · try it yourself
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" \
     -d '{"title":"  ","priority":null,"estimateHours":250}' | jq
{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "Invalid request content.",
  "instance": "/api/tasks"
}

Better, but still without field details. The Exception Handling lesson adds a handler that returns the field errors as JSON, like this:

bash · try it yourself
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" \
     -d '{"title":"  ","priority":null,"estimateHours":250}' | jq '.errors'
{
  "estimateHours": "must be less than or equal to 100",
  "priority": "must not be null",
  "title": "must not be blank"
}

Validating path variables and params

To validate simple parameters, put constraints directly on them. Since Spring Framework 6.1, built-in method validation applies them automatically for controllers:

java
@GetMapping
List<Task> list(@RequestParam @Min(1) @Max(100) int size) { ... }

@GetMapping("/{id}")
Task get(@PathVariable @Positive long id) { ... }

A violation now produces a HandlerMethodValidationException → 400.

Nested objects and lists

java
public record NewProject(
        @NotBlank String name,
        @Valid @NotEmpty List<NewTask> tasks) {}   // @Valid cascades into each element

Without @Valid on the field, the inner NewTask objects would not be checked at all.

Custom constraints

When a rule is specific to your domain, write your own annotation:

java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = TagValidator.class)
public @interface AllowedTag {
    String message() default "unknown tag";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class TagValidator implements ConstraintValidator<AllowedTag, String> {
    private static final Set<String> TAGS = Set.of("work", "home", "urgent");
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        return value == null || TAGS.contains(value);
    }
}

Tip: Validate shape (required, length, format) with annotations on the DTO. Validate business rules that need the database ("this title already exists") in the service, and report them with a 409 or 422.

Test yourself

What triggers bean validation of a @RequestBody parameter?

  1. Nothing; it is always validated
  2. Adding @Valid (or @Validated) to the parameter
  3. Annotating the controller with @Validation
  4. Calling validate() in the constructor

Which constraint rejects null, "" and " "?

  1. @NotNull
  2. @NotEmpty
  3. @NotBlank
  4. @Size(min = 1)

A field has only @Email. The JSON omits it. Is the object valid?

  1. No, @Email requires a value
  2. Yes, most constraints treat null as valid
  3. Only in tests
  4. It depends on the HTTP method