Spring Validation: declaring rules once and checking them everywhere
Bean Validation lets you write rules such as "not blank" or "at least 1" as annotations on fields and parameters, and check them with one call. Spring connects it to beans and controllers, so invalid input is rejected before your code runs. This page shows how the validator reads the rules, where @Valid and @Validated are needed, and the cases where validation silently does nothing.
Contents
How Bean Validation works in Spring
Input checks written by hand, such as if (name == null || name.isBlank())ConstraintViolation
Three layers are involved:
- Jakarta Validation API: the annotations (
,@NotBlank ,@Size ) and interfaces (@Email ,Validator ), in theConstraintValidator package. Version 3.1 is current.jakarta.validation - Hibernate Validator: the implementation that does the checking. Spring Boot 4.1's
brings Hibernate Validator 9.1 and an expression language library for message templates.spring-boot-starter-validation - Spring's integration:
exposes the validator as a bean,LocalValidatorFactoryBean checks parameters and return values of bean methods through a proxy, and Spring MVC validates request bodies and parameters before calling a controller.MethodValidationPostProcessor
Two annotations trigger validation, and they are not interchangeable:
| Annotation | From | Where it goes | What it does |
|---|---|---|---|
@Valid | Jakarta Validation | Fields, parameters, return values, container elements | Validate this object too: cascade into its own constraints |
@Validated | Spring | A bean class, or a controller parameter | On a class: switch on method validation for the bean. On a parameter: validate with the listed groups |
The built-in constraints cover most needs:
| Constraint | Checks | Accepts null |
|---|---|---|
@NotNull | Value is not null | No |
@NotEmpty | Not null, and length or size above 0 | No |
@NotBlank | Not null, and at least one non-whitespace character | No |
@Size(min, max) | Length of a string, size of a collection, map or array | Yes |
@Min@Max@Positive@PositiveOrZero | Numeric bounds | Yes |
@Email@Pattern(regexp) | String format | Yes |
@Past@Future@PastOrPresent | Dates and times relative to now | Yes |
@Null | Value is null | Only null |
The "accepts null" column is the most important part of this table. Every constraint except the null checks treats null as valid, so that each annotation checks one thing and they can be combined. A field that must be present and well-formed needs both, for example @NotNull @Email
Validating an object directly
The simplest use needs no annotations on beans at all: build a validator and pass it an object. The three signups below are chosen to show a valid object, one that breaks four rules, and one made of nulls, which reveals which constraints accept null:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Comparator;
import java.util.Locale;
import java.util.Set;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
public class ValidateObject {
record Signup(
@NotBlank String username,
@Email @NotNull String email,
@Size(min = 8, max = 64) String password,
@Min(13) @Max(120) int age) {
}
static void check(Validator validator, Signup signup) {
Set<ConstraintViolation<Signup>> violations = validator.validate(signup);
System.out.println(signup);
System.out.println(" " + violations.size() + " violation(s)");
violations.stream()
.sorted(Comparator.comparing((ConstraintViolation<Signup> v) ->
v.getPropertyPath().toString()))
.forEach(v -> System.out.println(" " + v.getPropertyPath() + " = "
+ v.getInvalidValue() + ": " + v.getMessage()));
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
try (var factory = new LocalValidatorFactoryBean()) {
factory.afterPropertiesSet();
Validator validator = factory.getValidator();
check(validator, new Signup("ann", "ann@example.com", "correct-horse", 30));
check(validator, new Signup(" ", "not-an-email", "short", 9));
check(validator, new Signup(null, null, null, 30));
}
}
}
Signup[username=ann, email=ann@example.com, password=correct-horse, age=30]
0 violation(s)
Signup[username= , email=not-an-email, password=short, age=9]
4 violation(s)
age = 9: must be greater than or equal to 13
email = not-an-email: must be a well-formed email address
password = short: size must be between 8 and 64
username = : must not be blank
Signup[username=null, email=null, password=null, age=30]
2 violation(s)
email = null: must not be null
username = null: must not be blank
- The first signup has 0 violations, so
returned an empty set.validate - The second broke all four rules at once, and each violation carries the property path, the invalid value and a message such as
. The validator does not stop at the first failure, which is what a form needs to show every error together.size must be between 8 and 64 - The third had 3 null fields but only 2 violations.
is null and has onlypassword , which accepts null, so a missing password passed.@Size failed onlyemail , not@NotNull .@Email - The set has no defined order, so the program sorts it by property path to give stable output.
The messages come from Hibernate Validator's built-in resource bundle, in the default locale; this program sets English so that the output does not depend on the machine. A template such as {jakarta.validation.constraints.Size.message}size must be between {min} and {max}LocalValidatorFactoryBeanMessageSourcemessages.properties
Nested objects and collections: @Valid cascades
Constraints on a nested object are not checked unless the field that holds it asks for it. An order with a broken address and a broken line item shows the difference, because the same data is valid or invalid depending on one annotation:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class CascadeValidation {
record Address(@NotBlank String city, @NotBlank String postcode) {
}
record Line(@NotBlank String sku, @Positive int quantity) {
}
record OrderWithoutValid(Address shipTo, List<Line> lines) {
}
record Order(
@Valid Address shipTo,
@NotEmpty List<@Valid Line> lines,
List<@NotBlank String> couponCodes) {
}
static void print(String label, Set<? extends ConstraintViolation<?>> found) {
System.out.println(label + ": " + found.size() + " violation(s)");
found.stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage())
.sorted()
.forEach(System.out::println);
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
Validator validator = factory.getValidator();
Address badAddress = new Address("", "");
List<Line> badLines = List.of(new Line("A-1", 2), new Line("", 0));
print("Without @Valid",
validator.validate(new OrderWithoutValid(badAddress, badLines)));
print("With @Valid",
validator.validate(new Order(badAddress, badLines, List.of("SAVE10", " "))));
print("Empty order",
validator.validate(new Order(new Address("Leeds", "LS1"), List.of(), null)));
}
}
}
Without @Valid: 0 violation(s)
With @Valid: 5 violation(s)
couponCodes[1].<list element>: must not be blank
lines[1].quantity: must be greater than 0
lines[1].sku: must not be blank
shipTo.city: must not be blank
shipTo.postcode: must not be blank
Empty order: 1 violation(s)
lines: must not be empty
- Without
, the order had 0 violations, although its address has two blank fields and one line has a blank SKU and a quantity of 0. The validator checked only constraints on@Valid itself, and it has none.OrderWithoutValid - With
on@Valid and on the element typeshipTo , it found 5. The paths show where:List<@Valid Line> ,shipTo.city ,lines[1].sku .lines[1].quantity is a container element constraint: it checks each string in the list, and the pathList<@NotBlank String> points to the blank second code.couponCodes[1].<list element>- An empty list passes
, because there is nothing to cascade into.@Valid on the list caught it.@NotEmpty
Forgetting @Valid
Method validation on Spring beans
Constraints can also go on method parameters and return values, so a service rejects bad calls whoever the caller is. Spring checks them in a proxy created by MethodValidationPostProcessor@Validated
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Locale;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
public class MethodValidation {
record Customer(@NotBlank String name, @Email String email) {
}
@Validated
static class CustomerService {
public String register(@Valid Customer customer) {
return "registered " + customer.name();
}
public String page(@Min(1) int page, @NotBlank String sort) {
return "page " + page + " sorted by " + sort;
}
public @NotNull String nickname(String name) {
return name.equals("ann") ? "annie" : null;
}
}
static class UnannotatedService {
public String register(@Valid Customer customer) {
return "registered " + customer.name();
}
}
@Configuration
static class Config {
@Bean
static MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Bean
CustomerService customerService() {
return new CustomerService();
}
@Bean
UnannotatedService unannotatedService() {
return new UnannotatedService();
}
}
interface Call {
String run();
}
static void attempt(String label, Call call) {
System.out.println(label);
try {
System.out.println(" returned: " + call.run());
} catch (ConstraintViolationException e) {
e.getConstraintViolations().stream()
.map(v -> " violation: " + v.getPropertyPath() + " " + v.getMessage())
.sorted()
.forEach(System.out::println);
}
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
CustomerService service = context.getBean(CustomerService.class);
Customer bad = new Customer("", "nope");
attempt("register(bad customer):", () -> service.register(bad));
attempt("page(0, \"\"):", () -> service.page(0, ""));
attempt("nickname(\"bob\"), return value checked:", () -> service.nickname("bob"));
attempt("Same call on a bean without @Validated:",
() -> context.getBean(UnannotatedService.class).register(bad));
}
}
}
register(bad customer):
violation: register.customer.email must be a well-formed email address
violation: register.customer.name must not be blank
page(0, ""):
violation: page.page must be greater than or equal to 1
violation: page.sort must not be blank
nickname("bob"), return value checked:
violation: nickname.<return value> must not be null
Same call on a bean without @Validated:
returned: registered
threwregister before its body ran. The paths name the method, the parameter and the field:ConstraintViolationException .register.customer.email broke the constraints written directly on the two parameters,page(0, "") and@Min(1) ; no wrapper object is needed.@NotBlank ran, returned null, and then failed:nickname("bob") on the return type is checked after the method returns, at@NotNull .nickname.<return value>- On
, the identicalUnannotatedService call returned normally with an invalid customer. Itsregister was ignored, because without@Valid on the class the bean gets no validation proxy.@Validated
Parameter names such as customerpagejavac -parametersregister.arg0.emailMethodValidationPostProcessorstaticthis
Validation groups
The same class often has different rules in different situations: a new product must not have an id yet, while an update must have one. Groups attach each constraint to one or more situations. The four runs below validate with different group lists, including the trap of leaving out Default
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.groups.Default;
import java.util.Locale;
public class ValidationGroups {
interface OnCreate {
}
interface OnUpdate {
}
record Product(
@Null(groups = OnCreate.class) @NotNull(groups = OnUpdate.class) Long id,
@NotBlank String name) {
}
static void run(Validator validator, String label, Product product, Class<?>... groups) {
var found = validator.validate(product, groups);
System.out.println(label + " -> " + found.size() + " violation(s)");
found.stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage())
.sorted()
.forEach(System.out::println);
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
Validator v = factory.getValidator();
Product newProduct = new Product(5L, "");
Product update = new Product(null, "");
run(v, "create, groups OnCreate", newProduct, OnCreate.class);
run(v, "create, groups OnCreate + Default", newProduct, OnCreate.class,
Default.class);
run(v, "update, groups OnUpdate + Default", update, OnUpdate.class, Default.class);
run(v, "no groups (Default only)", update);
}
}
}
create, groups OnCreate -> 1 violation(s)
id: must be null
create, groups OnCreate + Default -> 2 violation(s)
id: must be null
name: must not be blank
update, groups OnUpdate + Default -> 2 violation(s)
id: must not be null
name: must not be blank
no groups (Default only) -> 1 violation(s)
name: must not be blank
- With only
, the validator reportedOnCreate but not the blank name.id: must be null on@NotBlank has noname attribute, so it belongs togroups , andDefault was not requested.Default - With
andOnCreate , both problems were reported, which is what a create endpoint wants.Default - With
andOnUpdate , the update without an id failedDefault , and the name failed too.@NotNull - With no groups, only
ran: the group-specific id rules were skipped.Default
In Spring, pass groups with @Validated(OnCreate.class)Defaultinterface OnCreate extends Default {}
Custom constraints
When no built-in annotation fits, write a constraint: an annotation marked with @ConstraintConstraintValidator
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.LocalDate;
import java.util.Locale;
public class CustomConstraint {
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SkuValidator.class)
@interface Sku {
String message() default "must look like {prefix}-1234";
String prefix() default "SKU";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public static class SkuValidator implements ConstraintValidator<Sku, String> {
private String prefix;
@Override
public void initialize(Sku annotation) {
prefix = annotation.prefix();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true; // leave null checks to @NotNull
}
return value.matches(prefix + "-\\d{4}");
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateRangeValidator.class)
@interface ValidRange {
String message() default "must not be before the start date";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public static class DateRangeValidator implements ConstraintValidator<ValidRange, Booking> {
@Override
public boolean isValid(Booking booking, ConstraintValidatorContext context) {
if (booking.from() == null || booking.to() == null
|| !booking.to().isBefore(booking.from())) {
return true;
}
context.disableDefaultConstraintViolation();
String template = context.getDefaultConstraintMessageTemplate();
context.buildConstraintViolationWithTemplate(template)
.addPropertyNode("to")
.addConstraintViolation();
return false;
}
}
@ValidRange
record Booking(@Sku(prefix = "ROOM") String room, LocalDate from, LocalDate to) {
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
Validator validator = factory.getValidator();
Booking[] bookings = {
new Booking("ROOM-0042", LocalDate.of(2026, 5, 1), LocalDate.of(2026, 5, 4)),
new Booking("SKU-0042", LocalDate.of(2026, 5, 1), LocalDate.of(2026, 5, 4)),
new Booking("ROOM-7", LocalDate.of(2026, 5, 4), LocalDate.of(2026, 5, 1)),
};
for (Booking b : bookings) {
System.out.println(b);
validator.validate(b).stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage())
.sorted()
.forEach(System.out::println);
}
}
}
}
Booking[room=ROOM-0042, from=2026-05-01, to=2026-05-04]
Booking[room=SKU-0042, from=2026-05-01, to=2026-05-04]
room: must look like ROOM-1234
Booking[room=ROOM-7, from=2026-05-04, to=2026-05-01]
room: must look like ROOM-1234
to: must not be before the start date
- The first booking passed both rules.
failedSKU-0042 . The message template@Sku(prefix = "ROOM") was filled in with the annotation's own attribute, givingmust look like {prefix}-1234 .must look like ROOM-1234- The third booking failed both. The date check is a class-level constraint, because it needs two fields; it reported its violation on the property
throughto , so a form can show the error next to that field instead of at the top.buildConstraintViolationWithTemplate(...).addPropertyNode("to")
Every constraint annotation must declare messagegroupspayloadConstraintDefinitionExceptiontrue@NotNull
Validation in a REST controller
In Spring MVC, validation happens before the controller method runs, and an invalid request becomes a 400 response. Request bodies and simple parameters fail with different exceptions, so this Spring Boot application sends one valid and one invalid request of each kind:
package demo.validation.rest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
public class RestValidation {
record NewUser(@NotBlank String name, @Email @NotBlank String email) {
}
@RestController
static class UserController {
@PostMapping("/users")
String create(@Valid @RequestBody NewUser user) {
return "created " + user.name();
}
@GetMapping("/users/{id}")
String find(@PathVariable @Min(1) long id,
@RequestParam(defaultValue = "10") @Min(1) @Max(100) int size) {
return "user " + id + ", page size " + size;
}
}
@RestControllerAdvice
static class ValidationErrors {
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail body(MethodArgumentNotValidException e) {
Map<String, String> errors = new TreeMap<>();
e.getBindingResult().getFieldErrors()
.forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "request body is invalid");
problem.setProperty("errors", errors);
return problem;
}
@ExceptionHandler(HandlerMethodValidationException.class)
ProblemDetail params(HandlerMethodValidationException e) {
Map<String, String> errors = new TreeMap<>();
e.getParameterValidationResults().forEach(r -> errors.put(
r.getMethodParameter().getParameterName(),
r.getResolvableErrors().get(0).getDefaultMessage()));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "request parameters are invalid");
problem.setProperty("errors", errors);
return problem;
}
}
@Configuration
@EnableAutoConfiguration
@Import({UserController.class, ValidationErrors.class})
static class App {
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static void send(String label, HttpRequest request) throws Exception {
HttpResponse<String> r = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(label);
System.out.println(" " + r.statusCode() + " " + r.body());
}
public static void main(String[] args) throws Exception {
Locale.setDefault(Locale.ENGLISH);
SpringApplication app = new SpringApplication(App.class);
app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (ConfigurableApplicationContext context = app.run()) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
for (String json : new String[] {
"{\"name\":\"Ann\",\"email\":\"ann@example.com\"}",
"{\"name\":\"\",\"email\":\"not-an-email\"}"}) {
send("POST /users " + json, HttpRequest.newBuilder(URI.create(base + "/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json)).build());
}
for (String path : new String[] {"/users/7?size=20", "/users/0?size=500"}) {
send("GET " + path,
HttpRequest.newBuilder(URI.create(base + path)).build());
}
}
}
}
POST /users {"name":"Ann","email":"ann@example.com"}
200 created Ann
POST /users {"name":"","email":"not-an-email"}
400 {"detail":"request body is invalid","instance":"/users","status":400,"title":"Bad Request","errors":{"email":"must be a well-formed email address","name":"must not be blank"}}
GET /users/7?size=20
200 user 7, page size 20
GET /users/0?size=500
400 {"detail":"request parameters are invalid","instance":"/users/0","status":400,"title":"Bad Request","errors":{"id":"must be greater than or equal to 1","size":"must be less than or equal to 100"}}
- The valid body reached the controller, which returned
.created Ann - The invalid body failed
with@Valid @RequestBody . The handler collected the two field errors into aMethodArgumentNotValidException , the RFC 9457 error format that Spring builds in, and the client received a 400 withProblemDetail ."errors":{"email":...,"name":...} broke/users/0?size=500 on the path variable and@Min(1) on the request parameter. These constraints sit directly on the parameters, so Spring's built-in method validation, added in Spring Framework 6.1, raised@Max(100) instead. Its results name both parameters,HandlerMethodValidationException andid .size
Before Spring Framework 6.1, constraints on @PathVariable@RequestParam@ValidatedConstraintViolationException@ExceptionHandler@EnableAutoConfiguration
Choosing where to validate
| Situation | Use |
|---|---|
| A JSON request body | @Valid @RequestBodyMethodArgumentNotValidException |
| Path variables and query parameters | Constraints directly on the parameters; handle HandlerMethodValidationException |
| A service that must reject bad calls from any caller | @Validated |
| Nested objects and lists of objects | @ValidList<@Valid Line> |
| Different rules for create and update | Separate request records, or groups with @Validated(OnCreate.class) |
| A rule that compares two fields | A class-level custom constraint that reports on one property |
| A rule that needs the database, such as uniqueness | A check in the service, backed by a unique constraint in the database |
| Validation outside Spring, such as a batch file | A Validator |
Validation guards the edges of the application, but it is not a substitute for database constraints, which still hold when two requests write at the same time. For the proxies behind method validation, see