Bean Validation with @Valid and @Validated

Difficulty: Intermediate

Question

How do you validate incoming request data in Spring Boot, and what is the difference between @Valid and @Validated?

Answer

Never trust client input. A mobile app can send a null email, a negative amount, or a name that is a thousand characters long, and if you let that reach the database you will chase bugs for weeks. Bean Validation, the Jakarta Validation standard implemented by Hibernate Validator, lets you declare rules right on the fields of your request objects and have the framework enforce them before your business code runs.

In Boot 3 you add spring-boot-starter-validation, which is not included in the plain web starter. Then you annotate the DTO fields with constraints from jakarta.validation.constraints: @NotNull, @NotBlank for non-empty strings, @Size, @Min, @Max, @Email, @Pattern for regex, @Positive, @Past, and so on. Each accepts a message attribute. In the controller you put @Valid before the @RequestBody parameter. Spring then runs the validator after deserialisation and, if any constraint fails, throws MethodArgumentNotValidException, which by default yields a 400 response.

The analogy is airport security: validation is the check before boarding, so bad input never reaches the aircraft. Do it at the boundary, not deep inside the service, and keep entity classes free of web-specific validation where possible by validating DTOs.

Now @Valid versus @Validated. @Valid is the standard Jakarta annotation. It triggers validation on an object and cascades into nested objects when placed on a field, so an address field inside a student request is validated too. @Validated is Spring's own variant with two extra abilities. First, it supports validation groups, letting you apply different rules for create versus update, for instance requiring id only on update. Second, when placed on a class, it enables method-level validation for any Spring bean, so constraints on method parameters like @Min(1) on a service method argument are checked through an AOP proxy, throwing ConstraintViolationException. For path variables and request params in a controller, put @Validated on the controller class and constraints directly on the parameters.

Two exception types to distinguish: MethodArgumentNotValidException for failed @Valid @RequestBody objects, carrying a BindingResult with field errors, and ConstraintViolationException for method-level and parameter validation. Both should be handled centrally in a @ControllerAdvice to return a clean, consistent JSON structure listing each field and message rather than the default verbose error.

You can write custom constraints too. Create an annotation such as @ValidPhone with @Constraint(validatedBy = PhoneValidator.class), implement ConstraintValidator, and reuse it across DTOs. That is typical for domain-specific rules like Indian mobile numbers or PAN formats. Remember that validation is not a replacement for database constraints: keep unique and not-null rules in the schema too, because concurrent requests can pass validation and still collide.

Code examples

DTO validation with a custom error response

public record CreateStudentRequest(
        @NotBlank(message = "name is required") @Size(max = 80) String name,
        @NotBlank @Email String email,
        @Pattern(regexp = "^[6-9]\\d{9}
quot;, message = "invalid Indian mobile number") String phone, @Min(value = 1, message = "year must be 1-4") @Max(4) int year, @Valid Address address) { } // cascades into nested object @RestController @Validated class StudentController { @PostMapping("/students") public ResponseEntity<Void> create(@Valid @RequestBody CreateStudentRequest req) { return ResponseEntity.status(HttpStatus.CREATED).build(); } @GetMapping("/students/{id}") public String get(@PathVariable @Min(1) Long id) { return "ok"; } // needs @Validated on class } @RestControllerAdvice class ValidationHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handle(MethodArgumentNotValidException ex) { Map<String, String> errors = new LinkedHashMap<>(); ex.getBindingResult().getFieldErrors() .forEach(f -> errors.put(f.getField(), f.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); } }

Field errors are collected into a readable map for the client.

Key points

Common follow-up questions

Interview tips

Concepts covered

Bean Validation, Valid, Validated, MethodArgumentNotValidException

More Spring Boot questions