Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How do you implement data validation in Spring Boot?

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedJan 23, 2025
UpdatedNov 16, 2026
8 min read

Spring Boot validates data with Jakarta Bean Validation, implemented by Hibernate Validator. Add spring-boot-starter-validation, put constraint annotations such as @NotBlank, @Email and @Min on a DTO (a record works well), and mark the controller parameter with @Valid. When a constraint fails, Spring throws MethodArgumentNotValidException and you turn it into a 400 response.

Since Spring Boot 3 the annotations live in the jakarta.validation.constraints package. Older tutorials that import javax.validation only work on Spring Boot 2.x.

Table of Contents

  • Adding the validation starter
  • Built-in constraint annotations
  • Triggering validation in a controller
  • Returning clear validation errors
  • Writing a custom constraint
  • Validation groups for create and update
  • Validating nested objects and services
  • Frequently Asked Questions
    • What is the difference between @Valid and @Validated?
    • Why is my validation not running?
    • Which HTTP status should invalid input return?
    • Should I validate entities or DTOs?
  • Summary

Adding the validation starter

Boot does not include a validator by default. Add the starter, which brings in Hibernate Validator and the Jakarta Validation API.

xml

For Gradle, use implementation 'org.springframework.boot:spring-boot-starter-validation'. Boot then auto-configures a LocalValidatorFactoryBean, so you do not declare a validator bean yourself.

Built-in constraint annotations

The most common constraints are listed below. All of them accept a message attribute and a groups attribute.

AnnotationWhat it checks
@NotNullValue is not null (an empty string passes)
@NotBlankString is not null and has at least one non-whitespace character
@NotEmptyString, collection, map or array is not null and not empty
@Size(min, max)Length of a string or size of a collection
@Min, @Max, @PositiveNumeric bounds
@EmailValue looks like an email address
@Pattern(regexp)String matches a regular expression
@Past, @FutureDate is before or after now

For text fields prefer @NotBlank over @NotNull, because @NotNull accepts an empty string or spaces. Here is a request DTO written as a record:

java

Constraints on record components are applied to the component and its accessor, so validation works the same way as with a class that has getters.

Triggering validation in a controller

Validation only runs when you ask for it with @Valid (from jakarta.validation) or Spring's @Validated.

java

If any constraint fails, Spring throws MethodArgumentNotValidException before your method body runs. Boot's default error handling then returns a 400 Bad Request.

To validate path variables or request parameters, put @Validated on the controller class and add constraints directly on the parameters, for example @PathVariable @Positive long id. These failures raise ConstraintViolationException on older Spring versions and HandlerMethodValidationException from Spring Framework 6.1 onward, so handle the exception that your version throws.

Returning clear validation errors

The default 400 body is not very helpful, so most APIs add a @RestControllerAdvice. The version below returns a field-to-message map using RFC 9457 problem details, which Spring supports through ProblemDetail.

java

A request with an empty name and an invalid email now returns JSON like this:

json

If you extend ResponseEntityExceptionHandler and set spring.mvc.problemdetails.enabled=true, Spring produces a problem-detail response for these exceptions without custom code.

Writing a custom constraint

When the built-in annotations are not enough, create your own annotation and a ConstraintValidator.

java
java

Spring instantiates the validator as a bean-aware object, so you can inject services (for example a repository that checks uniqueness) through the constructor. Keep slow database checks out of validators when you can, because they run on every request.

Validation groups for create and update

Groups let one class carry different rules for different operations. Define marker interfaces, assign constraints to them, and select the group with @Validated.

java
java

@Valid cannot select a group; only @Validated can. Constraints without a groups attribute belong to the Default group and are skipped when you validate a custom group only, so list the groups you need explicitly.

Validating nested objects and services

Nested objects are only validated when the field carries @Valid. For example, an Address address field inside the DTO needs @Valid on it, and the same applies to each element through List<@Valid Item> items.

You can also validate method arguments in services. Put @Validated on the service class and constraints on the parameters. Spring wraps the bean in a proxy and throws ConstraintViolationException on failure, so the same self-invocation limit as @Transactional applies.

Frequently Asked Questions

What is the difference between @Valid and @Validated?

@Valid is the standard Jakarta annotation and cascades validation into nested objects. @Validated is Spring's variant that additionally supports validation groups and enables method-level validation on a class.

Why is my validation not running?

The usual causes are a missing spring-boot-starter-validation dependency, a missing @Valid on the parameter, or importing javax.validation on Spring Boot 3, which no longer recognises it.

Which HTTP status should invalid input return?

Return 400 Bad Request for malformed or constraint-violating input. Some teams use 422 Unprocessable Content for semantic errors, but be consistent across the API.

Should I validate entities or DTOs?

Validate request DTOs at the API boundary, and keep database constraints as the last line of defence. Hibernate can also validate entities before persisting, but DTO validation gives clearer client errors.

Summary

Add spring-boot-starter-validation, annotate DTO fields with jakarta.validation constraints, and use @Valid on @RequestBody parameters. Handle MethodArgumentNotValidException in a @RestControllerAdvice to return structured 400 responses. Use custom constraints for business rules, groups for create versus update, and @Valid on nested fields so the whole object graph is checked.

Share