# Bean Validation with @Valid and @Validated

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

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-validation-valid
Last updated: 2026-11-28

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}$", 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

- Boot 3 needs spring-boot-starter-validation and jakarta.validation imports.
- @Valid cascades into nested objects; @Validated supports groups and method-level validation.
- Two exceptions: MethodArgumentNotValidException and ConstraintViolationException.
- Keep database constraints as the last line of defence.

## Common follow-up questions

- How do you write a custom validator annotation?
- What are validation groups?
- Why is validation at the controller not enough?

## Interview tips

- Name both exception types and say where you handle them.
- Mention that database constraints still matter due to concurrency.

## Concepts covered

Bean Validation, Valid, Validated, MethodArgumentNotValidException

Previous: [@PathVariable vs @RequestParam vs @RequestBody](https://www.internhack.in/learn/interview/spring-boot-interview/spring-request-mapping-pathvariable-requestparam-requestbody) · Next: [Global Exception Handling with @ControllerAdvice](https://www.internhack.in/learn/interview/spring-boot-interview/spring-controlleradvice-global-exception-handling) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [ResponseEntity and Correct HTTP Status Codes](https://www.internhack.in/learn/interview/spring-boot-interview/spring-responseentity)
- [Spring Data JPA: Repositories, Derived Queries and @Query](https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries)
- [JPA Relationships and the N+1 Query Problem](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one)
- [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching)
- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)
- [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
