पाठ 9 / 25

Validating Input

Bean Validation on request bodies.

@Valid with constraint annotations

Annotate DTO fields with Bean Validation constraints (@NotBlank, @NotNull, @DecimalMin, @Size, @Email) and mark the parameter with @Valid; invalid input is rejected with 400 Bad Request before your method runs. Validate at the edge of the system, and keep database constraints too. By default the error body is Spring's generic error JSON; enabling problem details produces standard RFC 9457 responses.

An invalid body, default versus problem details, run

I packaged the demo with mvn package, started it with java -jar on port 8085 and called it with curl; the output is copied from that run. With default settings, an empty name and zero price return a generic 400 error body (its timestamp is from that run). Restarting with spring.mvc.problemdetails.enabled=true returns an RFC 9457 problem-details body instead.

curl -s -w " [%{http_code}]" -X POST -H "content-type: application/json" -d '{"name":"","price":0}' localhost:8085/api/products

Output:

default:
{"timestamp":"2026-10-02T00:10:13.574Z","status":400,"error":"Bad Request","path":"/api/products"} [400]
with spring.mvc.problemdetails.enabled=true:
{"detail":"Invalid request content.","instance":"/api/products","status":400,"title":"Bad Request"} [400]

Return field errors to clients

Customise the 400 response (for example with a handler for MethodArgumentNotValidException) to list which fields failed, so clients can fix input.

त्वरित जाँच: What triggers validation of a request body?

  • Adding a database index
  • Naming the class Valid
  • The @Valid annotation on the parameter, with constraints on the DTO fields
  • Returning ResponseEntity
Answer

The @Valid annotation on the parameter, with constraints on the DTO fields — @Valid plus constraint annotations.