Lesson 6 of 12 · 10 min · Building REST APIs

Validating requests with Bean Validation

Covers: Spring Boot 4.1 and Spring Framework 7 on Java 17 or newer with Jakarta Bean Validation. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • Add validation rules with annotations such as @NotBlank, @Size and @Email
  • Trigger validation with @Valid and @Validated
  • Validate path variables, query parameters and nested objects
  • Write a custom constraint
  • Understand the error produced and how to shape it

In simple words

Never trust what arrives from outside. A caller might send an empty name, a negative price or an email address that is not one. Validation is the bouncer at the door: you write the rules once next to the data ("name must not be blank, quantity at least 1"), and Spring checks every request against them before your business code runs, answering "400 Bad Request" with the list of problems if any rule fails.

Words to know

  • Constraint annotation: a marker such as @NotBlank that states a rule for a field.
  • Bean Validation: the standard Java specification for these annotations, now under Jakarta EE.
  • Validator: the engine that checks the rules (Hibernate Validator in Spring Boot).
  • Violation: one broken rule.

Setup

Add the starter:

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

It brings Hibernate Validator, the reference implementation of Jakarta Bean Validation. Note the packages: jakarta.validation.constraints.* (Spring Boot 3 and later; older code used javax.validation).

Constraint annotations on a request DTO

public record CreateCustomerRequest(
        @NotBlank @Size(max = 80) String name,
        @NotBlank @Email String email,
        @Pattern(regexp = "^[6-9]\\d{9}$", message = "must be a 10-digit Indian mobile number") String phone,
        @NotNull @Min(18) @Max(100) Integer age,
        @NotEmpty List<@NotBlank String> skills) {}

Common constraints:

Annotation Rule
@NotNull not null
@NotEmpty not null and not empty (strings, collections, maps, arrays)
@NotBlank not null and has at least one non-whitespace character (strings)
@Size(min, max) length of a string or size of a collection
@Min, @Max numeric minimum or maximum
@Positive, @PositiveOrZero, @Negative sign
@DecimalMin, @DecimalMax, @Digits(integer, fraction) decimals and money
@Email a plausible email format (loose; verify by sending an email)
@Pattern(regexp) matches a regular expression
@Past, @Future, @PastOrPresent dates and times
@AssertTrue boolean must be true

Every annotation accepts a message. Pick the right null rule: @Size and @Email treat null as valid, so combine with @NotNull or @NotBlank when the field is required. Use @NotBlank for text, not @NotNull, or "" passes. For validation of elements inside collections, put the annotation on the type argument: List<@NotBlank String>.

Triggering validation

Add @Valid to the @RequestBody parameter:

@PostMapping("/customers")
public ResponseEntity<CustomerResponse> create(@Valid @RequestBody CreateCustomerRequest request) {
    ...
}

If any constraint fails, Spring throws MethodArgumentNotValidException before your method runs, and the response is 400. By default the body lists the violations; you will shape it in the next lesson. For a form-bound object (not JSON), add a BindingResult parameter right after the validated one to inspect errors yourself.

Nested objects are validated only if you mark the field with @Valid:

public record CreateOrderRequest(
        @NotNull Long customerId,
        @Valid @NotNull AddressRequest shippingAddress,       // @Valid cascades into AddressRequest
        @Valid @NotEmpty List<OrderLineRequest> lines) {}     // validates each element

Path variables and query parameters

For parameters that are not objects, annotate them and put @Validated on the controller class so Spring wraps it in a method-validation proxy:

@RestController
@Validated
@RequestMapping("/orders")
public class OrderController {

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

    @GetMapping
    public List<OrderResponse> list(@RequestParam @Min(0) int page,
                                    @RequestParam @Min(1) @Max(100) int size) { ... }
}

A violation here throws a ConstraintViolationException (in recent Spring versions, built-in method validation can instead raise HandlerMethodValidationException), which you map to 400 in your exception handler. Without a handler, it surfaces as a 500, which is a common surprise.

Validating in other layers

Validation can protect any bean, not only controllers. A @Service class annotated with @Validated validates method parameters and return values, and @ConfigurationProperties classes can be validated at startup (the application refuses to start with bad configuration). For JPA entities, Hibernate runs the same constraints before insert and update, a last line of defence next to database constraints (NOT NULL, UNIQUE, CHECK). Do not rely on validation alone for uniqueness: checking "email not already used" in code races with other requests; enforce it with a unique index and handle the violation (409).

Groups

Different rules for create and update? Use validation groups:

public interface OnCreate {}
public interface OnUpdate {}

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

@PostMapping public ... create(@Validated(OnCreate.class) @RequestBody CustomerRequest r) { ... }

Often simpler: use separate DTOs (CreateCustomerRequest, UpdateCustomerRequest) and avoid groups.

Custom constraints

When no built-in rule fits (a valid GST number, a business rule across fields), write one.

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = GstinValidator.class)
public @interface Gstin {
    String message() default "invalid GSTIN";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class GstinValidator implements ConstraintValidator<Gstin, String> {
    private static final Pattern GSTIN =
            Pattern.compile("^\\d{2}[A-Z]{5}\\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || GSTIN.matcher(value).matches();   // null is left to @NotNull
    }
}

Use it as @Gstin String gstin. Validators are Spring-managed, so they can inject beans (for example to check the database). For a rule across several fields (end date after start date), put a custom constraint on the class, or use @AssertTrue boolean isDateRangeValid() on a record method.

Error responses

A failed @Valid produces a 400. Return a consistent, helpful error (the next lesson builds it): the field name, the rejected value if safe, and the message.

{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "Validation failed",
  "errors": [
    {"field": "email", "message": "must be a well-formed email address"},
    {"field": "age", "message": "must be greater than or equal to 18"}
  ]
}

Messages can be internationalised with ValidationMessages.properties (and {key} placeholders in annotations). Do not echo sensitive input (passwords) in errors.

Validation is not security

Validation checks format and business rules; it does not replace authorisation (is this user allowed to touch order 5?), output encoding or parameterised queries. Combine them: validate input at the edge, authorise in the service, and use prepared statements in the data layer. Also limit sizes (@Size(max=...), spring.servlet.multipart.max-file-size, request size limits) to protect against abuse.

Common mistakes

  • Forgetting @Valid, so nothing is checked.
  • Using @NotNull on a string when @NotBlank is needed.
  • Missing @Valid on nested objects and list elements.
  • Forgetting @Validated on a class when validating path or query parameters.
  • Old imports (javax.validation) with Boot 3 or 4.
  • Validating uniqueness only in code, leaving a race condition.
  • Returning default stack-trace-like errors to clients.

Try it yourself

  1. Add a request DTO with @NotBlank, @Email, @Min and @Size, and send invalid JSON to see the 400.
  2. Add a nested address object, first without @Valid on the field (not validated), then with it.
  3. Validate a path variable with @Positive and a query parameter with @Max, and handle ConstraintViolationException.
  4. Write a custom @Gstin constraint with a unit test of the validator.

Check yourself

What is the difference between @NotNull, @NotEmpty and @NotBlank?

@NotNull forbids null only; @NotEmpty forbids null and empty strings or collections; @NotBlank (strings only) also forbids strings of only whitespace.

How do you validate a nested object in a request?

Mark the nested field with @Valid so the validation cascades into it.

What must you add to validate @PathVariable and @RequestParam constraints?

Constraint annotations on the parameters and @Validated on the controller class (or rely on Spring's built-in method validation in recent versions).

Which exception is thrown when @Valid @RequestBody fails?

MethodArgumentNotValidException, mapped to 400 by default.

Interview questions

How do you validate input in a Spring Boot REST API?

Add spring-boot-starter-validation, annotate DTO fields with Jakarta constraints, put @Valid on @RequestBody parameters (and @Validated on controllers for parameter constraints), and handle the resulting exceptions centrally to return a clear 400.

Difference between @Valid and @Validated?

@Valid is the standard Jakarta annotation that triggers validation and cascades into nested objects; @Validated is Spring's variant that also supports validation groups and enables method-level validation on a class.

Can validation guarantee a unique email?

No. A check-then-insert is racy under concurrency; enforce uniqueness with a database unique constraint and translate the violation to a 409.

Summary

  • Add the validation starter and annotate DTO fields with Jakarta constraints.
  • Use @Valid on request bodies (and nested fields), and @Validated plus constraints for parameters.
  • Write custom constraints for domain rules; prefer separate DTOs to groups.
  • Return structured 400 errors; validation complements, not replaces, authorisation and database constraints.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.