@Valid on request bodies
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A create-product endpoint receives JSON from the internet. If the controller trusts it, a product with price -5.00 gets saved. Spring can check the body before your method runs.
@Valid @RequestBody runs the checks before your method
@Valid is an annotation from jakarta.validation that you put on a controller parameter, as in @Valid @RequestBody CreateProductRequest request. It makes Spring MVC check the record's constraints before your method runs; a body that breaks a rule gets a 400 Bad Request.
A client posts JSON to create a product. Spring reads it into a record, checks the rules, and only then calls your method. The example below sends one good request and one bad one.
Example 1 · CreateProductRequest.java, ProductController.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/product/CreateProductRequest.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Digits;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Pattern;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.constraints.Size;
public record CreateProductRequest( @NotBlank(message = "is required") @Pattern(regexp = "^[A-Z0-9-]{3,20}$", message = "must be 3-20 characters: A-Z, 0-9 or -") String sku,
@NotBlank(message = "is required") @Size(min = 2, max = 120, message = "must be {min}-{max} characters") String name,
@NotNull(message = "is required") @Positive(message = "must be a positive id") Long categoryId,
@NotNull(message = "is required") @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0") @Digits(integer = 8, fraction = 2, message = "must have at most 8 digits before the point and 2 after") BigDecimal price,
@PositiveOrZero(message = "must be 0 or more") Integer stock,
Boolean isActive) {
// Runs before validation: " Clean Code " is checked and stored as "Clean Code" public CreateProductRequest { sku = sku == null ? null : sku.strip(); name = name == null ? null : name.strip(); }}
// src/main/java/com/shoplite/lab/product/ProductController.javapackage com.shoplite.lab.product;
import java.net.URI;
import jakarta.validation.Valid;
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.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }
@PostMapping public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) { System.out.println("ProductController.create: " + request.sku()); ProductResponse created = productService.create(request); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(created.id()).toUri(); return ResponseEntity.created(location).body(created); }}$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "ACC-KB100", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:59:15.435Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
Server console:
ProductController.create: ACC-KB100
ProductService.create: saving ACC-KB100What this code does
@Valid @RequestBodymakes Spring validate the record beforecreateruns. The good request reaches the controller and the service and gets 201 with aLocationheader.- The bad request gets 400, and the server console has no
ProductController.createline for it: the method never ran.ProductServiceis the lab's in-memory stand-in for ShopLite's service. - Your timestamps differ. In PowerShell, call
curl.exeand escape the inner double quotes, as the @RequestBody lesson showed; Git Bash and macOS Terminal take the command as written.
Without this step every controller would repeat the same checks by hand, or worse, pass bad data to the service. With it, the controller and the service can trust the request: request.price() is never negative and request.name() is never blank.
Invalid requests are stopped early, so they cost almost nothing: no service call and no database query. The server console in the example proves it: the controller prints a line only for the good request.
Order of execution
Order of a validated request
Put the steps in the order Spring runs them for a POST with a JSON body.
MethodArgumentNotValidException and the default 400 response
MethodArgumentNotValidException is the exception Spring throws when a @Valid @RequestBody argument breaks a rule. It holds one field error per broken rule (the field, the rejected value and your message), and Spring turns it into a 400 response.
Spring answers a bad body with a 400 and a very short JSON. The command below sends the contract's bad product to the lab app.
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:59:15.435Z","status":400,"error":"Bad Request","path":"/api/v1/products"}Example 2 · src/main/resources/application.properties (development only)
Runs in: the validation-lab practice project (Spring Boot 4.1)
spring.application.name=validation-labspring.web.error.include-binding-errors=alwaysspring.web.error.include-message=always$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:00:02.151Z","status":400,"error":"Bad Request","message":"Validation failed for object='createProductRequest'. Error count: 3","errors":[{"objectName":"createProductRequest","field":"name","rejectedValue":"K","codes":["Size.createProductRequest.name","Size.name","Size.java.lang.String","Size"],"arguments":[{"arguments":null,"code":"name","codes":["createProductRequest.name","name"],"defaultMessage":"name"},120,2],"bindingFailure":false,"code":"Size","defaultMessage":"must be 2-120 characters"},{"objectName":"createProductRequest","field":"sku","rejectedValue":"kb 1","codes":["Pattern.createProductRequest.sku","Pattern.sku","Pattern.java.lang.String","Pattern"],"arguments":[{"arguments":null,"code":"sku","codes":["createProductRequest.sku","sku"],"defaultMessage":"sku"},[],{"arguments":null,"codes":["^[A-Z0-9-]{3,20}$"],"defaultMessage":"^[A-Z0-9-]{3,20}$"}],"bindingFailure":false,"code":"Pattern","defaultMessage":"must be 3-20 characters: A-Z, 0-9 or -"},{"objectName":"createProductRequest","field":"price","rejectedValue":-5.00,"codes":["DecimalMin.createProductRequest.price","DecimalMin.price","DecimalMin.java.math.BigDecimal","DecimalMin"],"arguments":[{"arguments":null,"code":"price","codes":["createProductRequest.price","price"],"defaultMessage":"price"},false,{"arguments":null,"codes":["0.00"],"defaultMessage":"0.00"}],"bindingFailure":false,"code":"DecimalMin","defaultMessage":"must be greater than 0"}],"path":"/api/v1/products"}What this code does
spring.web.error.include-binding-errors=always(Spring Boot 4 name; Boot 3 usedserver.error.include-binding-errors) adds every field error to the default body;include-messageadds the summary line.- Now the reasons are visible:
sku,nameandpricewith your messages. But the body is long, shows Spring's internal codes, and the message names the classcreateProductRequest. Use it only on your own computer, never in production. - The order of the three errors is not fixed. The Exception handling module builds a short
errorslist in the order of the request body.
Spring's DefaultHandlerExceptionResolver turns the exception into a 400 and logs one WARN line that starts with Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] ... with 3 errors. The default body is short on purpose: timestamp, status, error and path, with no list of fields, because details can leak class and method names.
That is fine while learning, not for a real API. The Exception handling module turns this exception into the ShopLite contract's validation-failed problem with an errors list of { field, message }.
Nested objects and lists need @Valid too: order items
Cascaded validation means checking the objects inside an object. Bean Validation does it only where @Valid is written, for example List<@Valid OrderItemRequest> items; without @Valid the inner constraints are ignored.
An order holds a list of items, and each item has its own rules. The first program sends bad items through @Valid; the second leaves @Valid out.
Example 3 · PlaceOrderRequest.java, OrderItemRequest.java, OrderCheckController.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/order/PlaceOrderRequest.javapackage com.shoplite.lab.order;
import java.util.List;
import jakarta.validation.Valid;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.Size;
public record PlaceOrderRequest( @NotNull(message = "is required") @Positive(message = "must be a positive id") Long customerId,
@NotNull(message = "is required") @Positive(message = "must be a positive id") Long addressId,
@NotNull(message = "is required") @Size(min = 1, max = 20, message = "must have {min}-{max} items") List<@Valid @NotNull(message = "must not be null") OrderItemRequest> items) {}
// src/main/java/com/shoplite/lab/order/OrderItemRequest.javapackage com.shoplite.lab.order;
import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Positive;
public record OrderItemRequest( @NotNull(message = "is required") @Positive(message = "must be a positive id") Long productId,
@NotNull(message = "is required") @Min(value = 1, message = "must be between 1 and 10") @Max(value = 10, message = "must be between 1 and 10") Integer quantity) {}
// src/main/java/com/shoplite/lab/order/OrderCheckController.javapackage com.shoplite.lab.order;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class OrderCheckController {
record OrderCheck(long customerId, int items, int units) { }
@PostMapping("/lab/orders/check") public OrderCheck check(@Valid @RequestBody PlaceOrderRequest request) { int units = request.items().stream().mapToInt(OrderItemRequest::quantity).sum(); return new OrderCheck(request.customerId(), request.items().size(), units); }}$ curl -i -X POST http://localhost:8080/lab/orders/check -H "Content-Type: application/json" -d '{"customerId": 1, "addressId": 1, "items": [{"productId": 9, "quantity": 1}, {"productId": 6, "quantity": 2}]}'
HTTP/1.1 200
Content-Type: application/json
{"customerId":1,"items":2,"units":3}
$ curl -i -X POST http://localhost:8080/lab/orders/check -H "Content-Type: application/json" -d '{"customerId": 1, "addressId": 1, "items": [{"productId": 9, "quantity": 0}, {"quantity": 2}]}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:59:17.689Z","status":400,"error":"Bad Request","path":"/lab/orders/check"}
$ curl -i -X POST http://localhost:8080/lab/orders/check -H "Content-Type: application/json" -d '{"customerId": 1, "addressId": 1, "items": []}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:59:17.873Z","status":400,"error":"Bad Request","path":"/lab/orders/check"}
Server console (shortened):
2026-10-16T11:29:17.676+05:30 WARN 27572 --- [validation-lab] [io-18611-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed ... [Field error in object 'placeOrderRequest' on field 'items[1].productId': rejected value [null]; ... default message [is required]] [Field error in object 'placeOrderRequest' on field 'items[0].quantity': rejected value [0]; ... default message [must be between 1 and 10]]What this code does
List<@Valid @NotNull OrderItemRequest>checks each item's own rules and rejects anullitem.@Size(min = 1, max = 20)checks the list itself, so"items": []is also a 400.- The WARN line (shortened here) names each broken item field by its position,
items[1].productIdanditems[0].quantity, with your message. /lab/orders/checkonly reports what passed validation. Real order placement, with prices and stock, is built in the ShopLite REST API module.
Example 4 · PlaceOrderRequest.java without @Valid on the items
Runs in: the validation-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.order;
import java.util.List;
import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.Size;
public record PlaceOrderRequest( @NotNull(message = "is required") @Positive(message = "must be a positive id") Long customerId,
@NotNull(message = "is required") @Positive(message = "must be a positive id") Long addressId,
@NotNull(message = "is required") @Size(min = 1, max = 20, message = "must have {min}-{max} items") List<OrderItemRequest> items) {}$ curl -i -X POST http://localhost:8080/lab/orders/check -H "Content-Type: application/json" -d '{"customerId": 1, "addressId": 1, "items": [{"productId": 9, "quantity": 0}, {"quantity": 2}]}'
HTTP/1.1 200
Content-Type: application/json
{"customerId":1,"items":2,"units":2}What this code does
- The same request as Example 3 now gets 200: an item with quantity 0 and an item with no product passed, because nothing asked for the items to be checked.
- The controller still has
@Valid, anditemsstill has@Size; only the cascade to the elements is missing. Adding@Validback on the element type restores the 400.
Without @Valid the order passes with an item of quantity 0 or with no productId, and the service has to deal with it, or crashes on it. With it, each broken item is reported with its position, such as items[0].quantity and items[1].productId.
The list itself has its own rules: @NotNull and @Size(min = 1, max = 20) check the list, and @Valid on the element type checks what is inside. Writing @Valid on the field (@Valid List<OrderItemRequest> items) also works; the element type is the modern style.
Constraints on record components
A compact constructor is a record constructor written without a parameter list. It runs whenever the record is created, so it is the place to clean input, for example name = name.strip();, before the constraints are checked.
Users often type spaces around a name. Because Jackson builds the record through its constructor, a clean-up step can run before validation. The example sends such a name.
Example 5 · Trimming in the compact constructor
Runs in: the validation-lab practice project (Spring Boot 4.1)
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": " BK-DSA ", "name": " Data Structures in Java ", "categoryId": 5, "price": 549.00}'curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "BK-X", "name": " K ", "categoryId": 5, "price": 549.00}'$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": " BK-DSA ", "name": " Data Structures in Java ", "categoryId": 5, "price": 549.00}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/17
Content-Type: application/json
{"id":17,"sku":"BK-DSA","name":"Data Structures in Java","categoryId":5,"categoryName":"Books","price":549.00,"stock":0,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "BK-X", "name": " K ", "categoryId": 5, "price": 549.00}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T05:59:15.899Z","status":400,"error":"Bad Request","path":"/api/v1/products"}What this code does
- The compact constructor in Example 1's
CreateProductRequeststripsskuandnamebefore validation, so" BK-DSA "is stored asBK-DSAand the response shows the clean values. " K "becomes"K", one character, so@Size(min = 2)rejects it. Without the strip, the spaces would count and" K "would pass as a 5-character name.
A record component is one of the values in a record's header, such as String sku. Constraint annotations written there are copied by the compiler to the private field, the accessor and the constructor parameter; Hibernate Validator checks the field.
The compact constructor makes " Clean Code " into "Clean Code" and makes " K " fail the 2-character minimum, as the API contract says ("strings are trimmed before checking"). Keep it to small, safe clean-ups such as trimming and defaults, and never throw from it for bad input: leave that to the constraints, so the client gets every problem in one response.
Forgetting @Valid: the silent bug where nothing is checked
If @Valid is missing, the record's constraints are never checked. The example removes it from the controller and sends the same bad product again.
Example 6 · ProductController.java without @Valid
Runs in: the validation-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.product;
import java.net.URI;
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.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }
@PostMapping public ResponseEntity<ProductResponse> create(@RequestBody CreateProductRequest request) { System.out.println("ProductController.create: " + request.sku()); ProductResponse created = productService.create(request); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(created.id()).toUri(); return ResponseEntity.created(location).body(created); }}$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
{"id":16,"sku":"kb 1","name":"K","categoryId":4,"categoryName":"Accessories","price":-5.00,"stock":0,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"name": " "}'
HTTP/1.1 500
Content-Type: application/json
{"timestamp":"2026-10-16T05:02:40.486Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}
Server console (shortened):
ProductController.create: kb 1
ProductService.create: saving kb 1
2026-10-16T10:32:40.457+05:30 ERROR 16924 --- [validation-lab] [io-18613-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "java.lang.L ...What this code does
- Only
@Validwas removed. The contract's bad product is now saved with 201: SKUkb 1, nameK, price -5.00. - The body with only a blank name reaches the service, which fails on the missing
categoryIdwith aNullPointerException, and the client gets a 500 instead of a clear 400. - Nothing in the log warned about the first request. That is why every endpoint needs a test that sends bad data.
The annotations on a record are only descriptions: forget @Valid (or Spring's @Validated) and the endpoint accepts everything, with no error, no warning and no log line. The damage shows up later and far away: a product with SKU kb 1 and price -5.00 saved with 201 Created, or a NullPointerException deep in the service that becomes a 500. Tests that only send good data never notice.
Two habits prevent it. Review every @RequestBody for @Valid, and keep one controller test per endpoint that sends a bad body and expects 400. A second trap: adding a BindingResult parameter after the body stops Spring from throwing, so you must check it yourself; practice 6 shows that bug.
Find the bug
Find the missing check
Each snippet accepts bad data. Click the line that causes it.
A product with price -5.00 is saved with 201.
Round 1 of 3Next step
Check your understanding
12 quick questions