🎯 What you will learn

Bean Validation (Jakarta Validation API) lets you declare constraints directly on your DTO fields — then a single @Valid annotation on the controller parameter tells Spring to enforce them before your method body runs. By the end of this lesson you will understand:

  • Declaring Java records as immutable, self-documenting request DTOs
  • Constraint annotations: @NotBlank, @Positive, @Max, @Pattern
  • Triggering validation with @Valid @RequestBody
  • The automatic 400 Bad Request Spring returns when constraints fail
  • Returning structured error bodies with @RestControllerAdvice (Lesson 23)
  • Response DTOs as records — no validation needed on output shapes
💼 Interview reality: "How do you validate incoming REST payloads?" is asked in every Spring Boot interview. Knowing the difference between @NotNull, @NotEmpty, and @NotBlank — and why you pair @Valid with @RequestBody — immediately signals senior-level fluency.

🌍 Real-world scenario

🌍
NairaSwift (Lagos, Nigeria)
Stop bad transfers at the front door

NairaSwift receives malformed POST bodies — missing sender accounts, negative amounts, wrong currency codes. Samuel adds Bean Validation so those requests are rejected with clear 400 messages before they reach the service layer, never polluting the ledger.

📦 Block 1 — DTO record with constraints

A Java record makes the perfect immutable DTO: constructor, getters, equals, hashCode, and toString are all auto-generated. Constraint annotations on record components work identically to regular class fields.

mvn spring-boot:run
TransferRequest.java / TransferResponse.javaLesson 22 · DTO records with constraints
app started — validation ready
:: Spring Boot :: (v3.3.5) Started NairaswiftApplication in 0.851 seconds (process running for 0.961)

Why records? A DTO record in one line replaces 30+ lines of boilerplate. The record components are effectively final, which prevents accidental mutation of incoming data anywhere in the request lifecycle.

✅ Block 2 — @Valid in controller + valid request

@Valid is the switch that activates constraint checking. Without it, Spring passes the deserialized object to your method regardless of its field values. With it, Spring runs the validator first — failures throw MethodArgumentNotValidException and return 400 automatically.

curl -s -u samuel:pass123 -X POST http://localhost:8765/api/transfers -H "Content-Type: application/json" -d '{"fromAccount":"NS-100005","toAccount":"NS-100006","amountNgn":75000,"currency":"NGN"}'
TransferController.javaLesson 22 · @Valid @RequestBody
REAL — valid request, 201 Created{ "id": 1003, "fromAccount": "NS-100005", "toAccount": "NS-100006", "amountNgn": 75000.0, "currency": "NGN", "status": "PENDING", "createdAt": "2026-04-26T20:37:42.925523" }

🚫 Block 3 — Invalid request → structured 400

When @Valid detects constraint violations, Spring collects all failures (not just the first) and throws MethodArgumentNotValidException. A @RestControllerAdvice handler (Lesson 23) formats them into a structured JSON body so mobile clients can display each field error individually.

curl -s -u samuel:pass123 -X POST http://localhost:8765/api/transfers -H "Content-Type: application/json" -d '{"fromAccount":"BADACCT","toAccount":"NS-100006","amountNgn":-500,"currency":""}'
BadRequest.java (comment)Lesson 22 · multiple constraint violations
REAL — 400 with all constraint violations{ "timestamp": "2026-04-26T20:37:46.642083", "status": 400, "error": "Validation Failed", "messages": [ "Account must match NS-XXXXXX", "Currency is required", "Amount must be positive" ] }

All violations at once: Spring collects every constraint failure before responding. This means the client gets a complete list of what to fix — not a frustrating one-error-at-a-time loop.

📋 Common constraint annotations

AnnotationWhat it checksWorks on
@NotNullValue must not be nullAny
@NotEmptyNot null and not empty (length > 0)String, Collection
@NotBlankNot null, not empty, not whitespace-onlyString
@PositiveStrictly > 0Numeric
@PositiveOrZero>= 0Numeric
@Min(n) / @Max(n)Value within boundsNumeric
@Pattern(regexp)Matches regexString
@EmailValid email formatString
@Size(min,max)Length / size within boundsString, Collection

🎤 Interview Q&A

EasyWhat is the difference between @NotNull, @NotEmpty, and @NotBlank?
+

@NotNull: value must not be null. @NotEmpty: not null and not empty (for Strings/Collections). @NotBlank: not null, not empty, and not whitespace-only. Use @NotBlank for user-facing String inputs.

EasyDo I need to add any dependency for Bean Validation in Spring Boot?
+

spring-boot-starter-validation includes Hibernate Validator, the reference implementation. Add it to pom.xml and the javax/jakarta validation annotations become available.

MediumHow do I validate nested objects in a DTO?
+

Annotate the nested field with @Valid. For example, if TransferRequest has a nested Address field, annotate it @Valid Address billingAddress so Address's constraints are also checked.

MediumHow do I write a custom constraint annotation?
+

Create a @Constraint annotation and a ConstraintValidator<A,T> implementation. The isValid() method receives the value and a ConstraintValidatorContext. Compose your business rule and return true/false.

HardHow does Bean Validation integrate with the Spring lifecycle?
+

When @Valid is present, Spring's MethodValidationInterceptor (or WebDataBinder for @RequestBody) calls the ValidatorFactory to obtain a Validator and invokes validate(). Violations are collected into BindingResult; if any exist and BindingResult is not in the method signature Spring throws MethodArgumentNotValidException, which propagates to exception handlers.

📝 Quiz — 5 questions

Question 1 of 5
Which annotation triggers Bean Validation on a @RequestBody?
Question 2 of 5
Which constraint ensures a String is not null and not blank?
Question 3 of 5
What HTTP status does Spring return by default when @Valid fails?
Question 4 of 5
Which annotation validates that a number is strictly greater than zero?
Question 5 of 5
Why use Java records as DTOs?
0
/ 5
Quiz complete!

Next: Error Handling and ResponseEntity →

⚠️ Common mistakes

Forgetting @Valid on the parameter
The DTO record can have all the annotations but Spring won't run them without @Valid on the method parameter. Always pair @Valid @RequestBody.
Using @NotNull instead of @NotBlank for Strings
@NotNull("") passes empty strings through. Use @NotBlank for any user-supplied String field.
Ignoring BindingResult
If you add BindingResult as a parameter, Spring won't throw; you must check it manually. Omit BindingResult to let Spring throw automatically.
Validating only on the DTO but not the entity
The DTO catches HTTP input errors; add @Valid / @Validated on service method parameters too if you call them programmatically.

✅ Key takeaways

  • spring-boot-starter-validation adds Jakarta Bean Validation via Hibernate Validator
  • Record DTOs + constraint annotations = concise, self-documenting input contracts
  • @Valid on @RequestBody triggers constraint checking; failures → 400 automatically
  • @NotBlank, @Positive, @Pattern, @Max cover the vast majority of field-level rules
  • Custom @Constraint annotations handle domain-specific rules (e.g., IBAN format)
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

Validate inputs. Ship safe APIs.

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →