Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 66 ยท Building REST APIs

Bean Validation

Validate request data in Spring Boot with @Valid and Jakarta constraints: built-in annotations, groups, custom constraints and method validation.

Never trust input. A client can send an empty name, a negative quantity, a date in the past or a ten-megabyte string, and your code must reject it before it reaches the database. You could write if statements at the top of every method, but that code is repetitive, easy to forget and impossible to read at a glance.

Bean Validation (Jakarta Validation) solves this declaratively: you put constraint annotations on the fields of a DTO, and a validator checks them. Spring Boot wires the standard implementation, Hibernate Validator, into the web layer, so a single @Valid on a controller parameter is enough. This lesson covers the built-in constraints, how errors surface, groups, custom constraints and validation of method parameters in services. The Java-level API is also covered in Validation and Error Handling; here we focus on Boot.

The real validator needs Hibernate Validator, which our site cannot run, so Spring code is read-only. The TryIts below build a small reflection-based validator that works the same way internally: it reads annotations at run time and checks values.

Adding validation to a controller

Add the validation starter (spring-boot-starter-validation), put constraints on the DTO, and add @Valid to the parameter:

Java
public record CreateUserRequest(
    @NotBlank @Size(max = 50) String name,
    @NotBlank @Email String email,
    @Min(18) @Max(120) int age,
    @NotNull @Past LocalDate birthday
) {}

@RestController
@RequestMapping("/users")
class UserController {

    @PostMapping
    ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
        return ResponseEntity.status(201).body(userService.create(request));
    }
}

When validation fails, Spring throws MethodArgumentNotValidException before your method body runs, and Boot answers 400 Bad Request. The exception carries every violation, not just the first, so a client can fix all problems in one round trip. You will turn that exception into a clean response in Error Handling and Problem Details.

Where validation can run

Request body @Valid on a @RequestBody DTO.
Parameters Constraints on path and query values.
Services @Validated on a bean checks method arguments.
Config Properties classes can be validated at startup.
1 / 2

The built-in constraints

The jakarta.validation.constraints package gives you the everyday set. Remember the package: Boot 2 used javax.validation, Boot 3 and later use jakarta.validation.

Annotation Checks Notes
@NotNull value is not null allows an empty string
@NotEmpty not null, length or size above 0 strings, collections, maps
@NotBlank not null and has a non-whitespace character strings only
@Size(min, max) length of a string or size of a collection null passes
@Min, @Max numeric bounds null passes
@Positive, @PositiveOrZero sign checks
@Email looks like an email address lenient; it is not proof the mailbox exists
@Pattern(regexp) matches a regular expression null passes
@Past, @Future date is before or after now
@Valid validate the nested object too cascades into fields

Most constraints treat null as valid. They check a value if there is one, so pair them with @NotNull or @NotBlank when the field is required. Forgetting that pairing is the most common validation bug: @Size(min = 3) on a missing field passes.

Nested objects and collections

Constraints on a nested DTO only run if you add @Valid to the field that holds it. The same works for collection elements through type annotations:

Java
public record OrderRequest(
    @NotBlank String customer,
    @Valid @NotNull AddressRequest shippingAddress,
    @NotEmpty List<@Valid OrderLine> lines
) {}

A reflection validator, step by step

Hibernate Validator is large, but the core idea is small: find the annotations, read the value, apply a rule, collect the violations. The first TryIt builds that idea with our own annotations on a record. Each rule has a message, the validator never stops at the first problem, and a field that is not required passes when it is null, just like the real constraints.

Java A mini validator over annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real here: constraints are annotations kept at run time, a validator reads them with reflection, and one pass reports all violations. What is the stand-in: the real engine supports dozens of constraints, nested cascading, message templates with internationalization, and caches the metadata so it is fast.

Custom constraints

When no built-in annotation fits, write your own. A custom constraint is two pieces: an annotation, and a class that implements ConstraintValidator.

Java
@Target({FIELD, PARAMETER, RECORD_COMPONENT})
@Retention(RUNTIME)
@Constraint(validatedBy = SlugValidator.class)
public @interface Slug {
    String message() default "must be a lowercase slug such as spring-boot";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class SlugValidator implements ConstraintValidator<Slug, String> {

    private static final Pattern SLUG = Pattern.compile("[a-z0-9]+(-[a-z0-9]+)*");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || SLUG.matcher(value).matches();
    }
}

The three attributes message, groups and payload are required by the specification. Return true for null so that required-ness stays the job of @NotNull. Because Spring creates validators as beans, a ConstraintValidator can even have a service injected, for example to check that an email address is not already registered. Keep such database checks in mind though: a check-then-insert has a race condition, and a unique index in the database is the real guarantee.

Groups

Sometimes the rules differ by operation. An id must be absent when creating a record and present when updating it. Validation groups let you tag constraints with a marker interface and choose which group to run.

Java
public interface OnCreate {}
public interface OnUpdate {}

public record BookRequest(
    @Null(groups = OnCreate.class) @NotNull(groups = OnUpdate.class) Long id,
    @NotBlank(groups = {OnCreate.class, OnUpdate.class}) String title
) {}

@PostMapping
ResponseEntity<Book> create(@Validated(OnCreate.class) @RequestBody BookRequest body) { ... }

@PutMapping("/{id}")
ResponseEntity<Book> update(@Validated(OnUpdate.class) @RequestBody BookRequest body) { ... }

Spring's @Validated (unlike plain @Valid) accepts the group list. Many teams skip groups and use two DTOs, CreateBookRequest and UpdateBookRequest, which is simpler to read and cannot be mixed up. Use groups when the two shapes truly share almost every field.

The second TryIt models groups: each rule is tagged with the operation it belongs to, and the validator runs only the rules of the chosen group.

Java Rules that depend on the operation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Validating outside the web layer

Constraints are not limited to controllers. Put @Validated on a Spring bean and constraints on its method parameters (or return value) are enforced through a proxy:

Java
@Service
@Validated
class TransferService {

    void transfer(@NotBlank String fromAccount,
                  @NotBlank String toAccount,
                  @Positive BigDecimal amount) {
        // ...
    }
}

A violation here throws ConstraintViolationException. Since Spring Framework 6.1, controller methods get built-in method validation too: constraints placed directly on controller parameters (@RequestParam @Min(1) int page) work without @Validated on the class and fail with HandlerMethodValidationException. Validation of @ConfigurationProperties classes uses the same constraints and stops the application at startup if a required property is missing, which you will meet in Type-Safe @ConfigurationProperties.

Validation protects the shape of data, not its trustworthiness. It does not replace authorization, escaping on output, or database constraints. Keep NOT NULL, UNIQUE and foreign keys in the schema as well: validation can be bypassed by anything that does not go through your controller.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A field has @Size(min = 3) and the client omits it, so the value is null. What happens?

    Constraints such as @Size, @Min and @Pattern check a value only when one is present. Add @NotNull or @NotBlank to make the field required.
  2. 2. Why does @Valid on a parameter validate only the top-level fields of a nested DTO unless you add something?

    Validation does not descend into fields on its own. Putting @Valid on the field that holds the nested object tells the validator to cascade into it.
  3. 3. Which exception signals that a @Valid @RequestBody DTO failed validation?

    Spring throws MethodArgumentNotValidException with all violations before the controller method runs. HttpMessageNotReadableException is for malformed JSON.
  4. 4. What are validation groups useful for?

    Constraints are tagged with marker interfaces, and @Validated(OnCreate.class) runs only that group's rules.
  5. 5. Why should a custom ConstraintValidator return true for null?

    Following the convention keeps each constraint focused on one thing. Combine it with @NotNull when the value is required.

Summary

  • Add spring-boot-starter-validation, put Jakarta constraints on DTOs and use @Valid on @RequestBody parameters.
  • Most constraints accept null; pair them with @NotNull or @NotBlank for required fields.
  • Cascade into nested objects and collection elements with @Valid.
  • Write custom constraints as an annotation plus a ConstraintValidator, returning true for null.
  • Use groups (with @Validated) or separate DTOs for create-versus-update rules.
  • @Validated on a bean enforces method-parameter constraints; the database must still enforce its own constraints.

Next: Error Handling and Problem Details.