@NotBlank, @Size, @Valid — validate request bodies without boilerplate.
Published February 8, 2025
Spring Boot integrates with the Jakarta Bean Validation API (formerly javax.validation). Add spring-boot-starter-validation and annotate your request objects.
public record CreateUserRequest(
@NotBlank(message = "Name is required")
String name,
@Email(message = "Must be a valid email")
@NotBlank
String email,
@Size(min = 8, message = "Password must be at least 8 characters")
@NotBlank
String password,
@Min(18) @Max(120)
int age
) {}
@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public UserDto createUser(@RequestBody @Valid CreateUserRequest request) {
// if validation fails, MethodArgumentNotValidException is thrown
return userService.create(request);
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> fieldErrors = ex.getBindingResult()
.getFieldErrors()
.stream()
.collect(Collectors.toMap(
FieldError::getField,
e -> e.getDefaultMessage() != null ? e.getDefaultMessage() : "Invalid value"
));
return Map.of(
"status", 400,
"error", "Validation Failed",
"errors", fieldErrors
);
}
}
| Annotation | Description |
|---|---|
@NotNull | Must not be null |
@NotBlank | Must not be null, empty, or whitespace |
@NotEmpty | Must not be null or empty |
@Size(min, max) | String/collection length range |
@Min / @Max | Numeric bounds |
@Email | Valid email format |
@Pattern(regexp) | Matches regex |
@Positive | Number > 0 |
@Future / @Past | Date constraint |
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SlugValidator.class)
public @interface ValidSlug {
String message() default "Must be a valid slug (lowercase, hyphens only)";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Annotate your DTOs, trigger with @Valid at the controller, handle MethodArgumentNotValidException in a @RestControllerAdvice. This shows you understand the Spring validation pipeline end-to-end.