Add validation module: Bean Validation on Spring Boot 4.2.0 with Hibernate Validator 9.1.6, built-in and custom constraints, groups, method validation, ProblemDetail errors, message i18n, JPA integration and tests, with real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4RzcCS5JCAgcxLz7T
This commit is contained in:
Claude
2026-12-05 16:18:03 +05:30
parent a95f042051
commit 417903fbc2
78 changed files with 2279 additions and 0 deletions
+1
View File
@@ -9,6 +9,7 @@ files.
| Directory | Article | What it demonstrates |
|---|---|---|
| [`validation/`](validation) | [Bean Validation in Spring Boot 4: Built-in Constraints, Custom Validators, Groups and ProblemDetail Errors](https://ankurm.com/custom-validation-in-spring-boot-beyond-the-basics/) | Hibernate Validator 9.1.6 on Boot 4.2.0: what every built-in constraint does with null and a bad value, custom and cross-field constraints, groups, method validation, one ProblemDetail shape for all three exceptions, French messages, JPA integration, the `BindingResult` + `toMap` 500, and the empty error body that only MockMvc shows |
| [`boot-versions/`](boot-versions) | [Spring Boot Versions: Release Dates, End of Support (4.0 Ends Dec 31, 2026) and Java Baselines](https://ankurm.com/spring-boot-versions/) | versions and release dates read from Maven Central and support dates from `api.spring.io`, one app built against 2.7.18 to 4.2.0 and booted on JDK 8 to 27, 3.5+ failing below Java 17 while a `--release 11` build still says `BUILD SUCCESS`, 2.7.18 failing to scan Java 25 classes, `layertools` gone after 4.0, jOOQ managed by 4.1+ needing Java 21, and a configuration-property diff from 4.0.10 to 4.2.0 |
| [`openfeature/`](openfeature) | [Feature Flags in Spring Boot with OpenFeature and flagd: Targeting, Gradual Rollout and Failure Modes](https://ankurm.com/spring-boot-feature-flags-openfeature-flagd/) | the OpenFeature Java SDK 1.23.0 and flagd 0.19.0 behind Spring Boot 4.2.0: five flag types and their reasons, targeting by tier and e-mail domain, a 10% rollout measured on 1000 users (100 on, and 0 flipped off when widened to 50%), a flag file edited under a connected client, flagd absent at start (`PROVIDER_NOT_READY`) and killed mid-run (targeted flags fall back to the code default while a static flag keeps answering `CACHED`), unknown keys and type mismatches, `InMemoryProvider` tests of both states and the in-process `FILE` resolver giving the same 100 of 1000 |
| [`resttemplate-to-restclient/`](resttemplate-to-restclient) | [RestTemplate Is Deprecated in Spring Framework 7.1: Migrate to RestClient (and TestRestTemplate to RestTestClient)](https://ankurm.com/resttemplate-to-restclient-migration-guide/) | the `[removal]` warnings on 4.2.0 vs none on 4.1.3, every `RestTemplate` method next to its `RestClient` call on one real server, `exchange()` that stops throwing, the `RestClient.create(restTemplate)` bridge that changes URI encoding, PATCH and `User-Agent` of each default stack, an interceptor that eats the body, `TestRestTemplate` vs `RestTestClient`, and the OpenRewrite recipe's output run for real |
+34
View File
@@ -0,0 +1,34 @@
# validation
Companion code for [Bean Validation in Spring Boot 4](https://ankurm.com/custom-validation-in-spring-boot-beyond-the-basics/) on ankurm.com.
Built and run with Spring Boot 4.2.0, Spring Framework 7.1.0, Hibernate Validator 9.1.6.Final,
Jakarta Validation 3.1.1, Hibernate ORM 7.4.15.Final and JDK 25.0.5.1.
```bash
mvn test # 23 tests, which also rewrite most of output/
./scripts/run-all.sh # everything in output/, including the plain-Java, javac and Boot 4.1.3 runs
mvn spring-boot:run # the endpoints in web/ on :8080
```
`app.problem-advice=false` switches the `@RestControllerAdvice` off so you can see the defaults.
## Where things are
| Topic | Source | Output |
|---|---|---|
| Versions on the classpath | `pom.xml` | `00` |
| Built-in constraints, null handling, mistakes | `ConstraintCheatSheetTest` | `01`, `02` |
| Custom constraints, injection into validators | `constraint/`, `CustomConstraintTest` | `03` |
| Cascading, records, container elements | `model/`, `CustomConstraintTest` | `04`, `19`, `21` |
| Cross-field constraints | `DateRange*`, `PasswordsMatch*` | `05` |
| Groups, sequences, group conversion | `Groups`, `GroupsTest` | `06`, `12` |
| Method validation on services | `service/`, `MethodValidation*Test` | `07`, `08` |
| HTTP defaults and ProblemDetail | `web/`, `WebDefaultsTest`, `ProblemAdviceTest` | `09`, `10`, `11`, `22` |
| The `BindingResult` + `toMap` pitfalls | `BindingResultController` | `13` |
| Message sources and i18n, template safety | `messages*.properties`, `MessagesTest`, `ElInjectionTest` | `14`, `15`, `16` |
| Hibernate ORM integration | `jpa/`, `JpaIntegrationTest` | `17` |
| Testing | `ValidationSliceTest`, `DateRangeValidatorUnitTest`, `MockMvcEmptyBodyTest` | `18` |
| Hibernate Validator without Spring | `examples/plain-java/` | `20` |
The older [`custom-validation`](../custom-validation) module (Boot 4.1.1) stays as it was.
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm</groupId>
<artifactId>validation-plain-java</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- The engine. It brings jakarta.validation-api with it. -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>9.1.6.Final</version>
</dependency>
<!-- A Jakarta Expression Language implementation, needed by the default message interpolator. -->
<dependency>
<groupId>org.glassfish.expressly</groupId>
<artifactId>expressly</artifactId>
<version>6.0.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,25 @@
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
/** Hibernate Validator with no framework. Run with the argument "no-el" to skip the EL requirement. */
public class PlainJava {
record User(@Size(min = 3, message = "need {min} characters, got ${validatedValue}") String name) { }
public static void main(String[] args) {
var config = Validation.byDefaultProvider().configure();
if (args.length > 0) {
config.messageInterpolator(new ParameterMessageInterpolator());
}
// Building a factory is expensive: build one per application, close it on shutdown.
// The Validator it hands out is thread-safe.
try (ValidatorFactory factory = config.buildValidatorFactory()) {
Validator validator = factory.getValidator();
validator.validate(new User("ab")).forEach(v ->
System.out.println(v.getPropertyPath() + ": " + v.getMessage()));
}
}
}
@@ -0,0 +1,23 @@
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
/** Where does an annotation end up when its @Target omits RECORD_COMPONENT? */
public class RecordTarget {
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldOnly { }
record Message(@FieldOnly String text) { }
public static void main(String[] args) throws Exception {
System.out.println("compiled: @Target(FIELD) annotation on a record component");
System.out.println("on the record component: "
+ Arrays.toString(Message.class.getRecordComponents()[0].getAnnotations()));
System.out.println("on the private field: "
+ Arrays.toString(Message.class.getDeclaredField("text").getAnnotations()));
}
}
+8
View File
@@ -0,0 +1,8 @@
jakarta.validation:jakarta.validation-api:jar:3.1.1:compile
org.apache.tomcat.embed:tomcat-embed-el:jar:11.0.27:compile
org.hibernate.orm:hibernate-core:jar:7.4.15.Final:compile
org.hibernate.validator:hibernate-validator:jar:9.1.6.Final:compile
org.junit.jupiter:junit-jupiter-api:jar:6.1.3:test
org.springframework.boot:spring-boot:jar:4.2.0:compile
org.springframework:spring-core:jar:7.1.0:compile
openjdk version "25.0.5.1" 2026-11-17 LTS
@@ -0,0 +1,38 @@
== a sample value for each constraint (property: value -> result)
notNull "" valid
isNull "" must be null
notEmpty " " valid
notEmpty "" must not be empty
notBlank " " must not be blank
assertTrue false must be true
assertFalse true must be false
size "abcde" size must be between 2 and 4
min 9 must be greater than or equal to 10
max 11 must be less than or equal to 10
decimalMin 0.0 must be greater than 0.0
decimalMax 100 must be less than or equal to 99.99
digits 1.234 numeric value out of bounds (<3 digits>.<2 digits> expected)
positive 0 must be greater than 0
positiveOrZero -1 must be greater than or equal to 0
negative 0 must be less than 0
negativeOrZero 1 must be less than or equal to 0
past today must be a past date
pastOrPresent tomorrow must be a date in the past or in the present
future today must be a future date
futureOrPresent yesterday must be a date in the present or in the future
pattern "ABCD" must match "[A-Z]{3}"
email "not-an-email" must be a well-formed email address
email "a@b" valid
email "" valid
length "abcde" length must be between 2 and 4
range 6 must be between 1 and 5
url "ankurm.com" must be a valid URL
uuid "1234" must be a valid UUID
creditCard "4111111111111112" invalid credit card number
unique [a, a] must only contain unique elements
ip "999.1.1.1" invalid IP address
== which constraints reject null? (every other field left null)
rejects null: notBlank
rejects null: notEmpty
rejects null: notNull
@@ -0,0 +1,12 @@
== @Size on an Integer compiles, and fails when first validated
jakarta.validation.UnexpectedTypeException
HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Size' validating type 'java.lang.Integer'. Check configuration for 'quantity'
== @NotBlank on an Integer
HV000030: No validator could be found for constraint 'jakarta.validation.constraints.NotBlank' validating type 'java.lang.Integer'. Check configuration for 'quantity'
== an unescaped dot in @Email(regexp): value a@bcom
strict: must be a well-formed email address
== @Positive plus @Min(18) on age = -1 reports both
age: must be greater than 0 | age: must be greater than or equal to 18
@@ -0,0 +1,20 @@
== @CaseCheck(UPPER) "abc", @CaseCheck(LOWER) "abc"
upper: Wrong letter case
== a null value passes the custom rule
(no violations)
== short spam message
message: Message contains 'spam' and must be at least 50 characters long.
== long message containing spam
(no violations)
== a composed constraint with @Target(FIELD) only, used on a record component
name: must not be blank
== validator with a constructor-injected bean, username admin
username: That username is taken
== same object, validator built by hand without Spring
ValidationException: HV000064: Unable to instantiate ConstraintValidator: com.ankurm.validation.constraint.AvailableUsernameValidator.
@@ -0,0 +1,14 @@
== nested object with @Valid
item.name: must not be blank
== nested object without @Valid
(no violations)
== List<@Valid Item>
items[1].name: must not be blank
== @Valid List<Item>
items[1].name: must not be blank
== List<@NotBlank String> and a nested record, all wrong
address.city: must not be blank | address.pinCode: PIN code must be 6 digits | roles[1].<list element>: must not be blank
+11
View File
@@ -0,0 +1,11 @@
== @DateRange moves its violation onto endDate
endDate: End date must be after start date
== @DateRange with a missing date: only @NotNull speaks
endDate: must not be null
== @PasswordsMatch keeps the default object-level violation
<object>: Passwords do not match
== class-level constraint while a field is also invalid
<object>: Passwords do not match | password: size must be between 8 and 2147483647
+16
View File
@@ -0,0 +1,16 @@
== new ProductRequest(id=null, name=" ", price=-5)
validate(p) price: must be greater than 0
validate(p, OnCreate) name: must not be blank
validate(p, OnUpdate) id: must not be null | name: must not be blank
validate(p, Default, OnUpdate) id: must not be null | name: must not be blank | price: must be greater than 0
validate(p, Update extends Default) price: must be greater than 0
== @GroupSequence({Default, Expensive}): name blank, password short
name: must not be blank
== same sequence once the name is fixed
password: size must be between 8 and 2147483647
== cascade: nested rule is in OnUpdate, parent validated with Default
@Valid (no violations)
@Valid @ConvertGroup line.id: must not be null
@@ -0,0 +1,21 @@
service is an AOP proxy: true
== createUser(good, "")
jakarta.validation.ConstraintViolationException
createUser.creatorToken: must not be blank
== createUser(null, "token")
jakarta.validation.ConstraintViolationException
createUser.user: must not be null
== displayName(0) - the RETURN value is invalid
jakarta.validation.ConstraintViolationException
displayName.<return value>: must not be blank
== createViaThis(good) - calls createUser(user, "") on this
returned: created ravi
no exception
== implementation adds @NotNull that the interface lacks
jakarta.validation.ConstraintDeclarationException
HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method StricterGreeter#greet(String) redefines the configuration of Greeter#greet(String).
@@ -0,0 +1,3 @@
== spring.validation.method.adapt-constraint-violations=true, createUser(good, "")
org.springframework.validation.method.MethodValidationException
creatorToken: must not be blank
+19
View File
@@ -0,0 +1,19 @@
== POST /contacts {"email":"[email protected]","message":"This is spam."}
HTTP 400 application/json
{"timestamp":"...","status":400,"error":"Bad Request","path":"/contacts"}
== GET /users?size=0&sort=name
HTTP 400 application/json
{"timestamp":"...","status":400,"error":"Bad Request","path":"/users"}
== POST /contacts/bulk [{"email":"[email protected]","message":"This is spam."}]
HTTP 400 application/json
{"timestamp":"...","status":400,"error":"Bad Request","path":"/contacts/bulk"}
== GET /legacy?size=0
HTTP 500 application/json
{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/legacy"}
== POST /users/internal {}
HTTP 500 application/json
{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/users/internal"}
@@ -0,0 +1,7 @@
== POST /contacts {"email":"[email protected]","message":"This is spam."}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request"}
== GET /users?size=0&sort=name
HTTP 400 application/problem+json
{"detail":"Validation failure","status":400,"title":"Bad Request"}
@@ -0,0 +1,27 @@
== POST /users {"username":"admin","email":"nope","age":15,"roles":["dev"],"address":{"city":"Mumbai","pinCode":"4007"}}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"address.pinCode","code":"Pattern","message":"PIN code must be 6 digits"},{"field":"age","code":"Min","message":"Minimum age is 18"},{"field":"email","code":"Email","message":"Enter a work e-mail such as [email protected]"},{"field":"username","code":"AvailableUsername","message":"That username is taken"}]}
== GET /users?size=0&sort=name
HTTP 400 application/problem+json
{"detail":"Validation failure","status":400,"title":"Bad Request","errors":[{"field":"size","code":"Min","message":"must be greater than or equal to 1"}]}
== POST /contacts/bulk [{"email":"[email protected]","message":"This is spam."}]
HTTP 400 application/problem+json
{"detail":"Validation failure","status":400,"title":"Bad Request","errors":[{"field":"[0].message","code":"SpamMessageCheck","message":"Message contains 'spam' and must be at least 50 characters long."}]}
== POST /password {"password":"correct-horse","confirmation":"nope"}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":null,"code":"PasswordsMatch","message":"Passwords do not match"}]}
== POST /users/internal {}
HTTP 400 application/problem+json
{"detail":"Validation failure","status":400,"title":"Bad Request","errors":[{"field":"createUser.creatorToken","code":"NotBlank","message":"must not be blank"},{"field":"createUser.user.address","code":"NotNull","message":"must not be null"},{"field":"createUser.user.age","code":"NotNull","message":"must not be null"},{"field":"createUser.user.email","code":"NotBlank","message":"must not be blank"},{"field":"createUser.user.roles","code":"NotEmpty","message":"must not be empty"},{"field":"createUser.user.username","code":"NotBlank","message":"Username is required"}]}
== POST /bookings {"startDate":"2026-05-10","endDate":"2026-05-01"}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"endDate","code":"DateRange","message":"End date must be after start date"}]}
== POST /bookings {"startDate":"10/05/2026"}
HTTP 400 application/problem+json
{"detail":"Failed to read request","status":400,"title":"Bad Request"}
+11
View File
@@ -0,0 +1,11 @@
== POST /products {"id":7,"name":"Pen","price":10}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"id","code":"Null","message":"must be null"}]}
== PUT /products {"name":"Pen","price":-1}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"id","code":"NotNull","message":"must not be null"},{"field":"price","code":"Positive","message":"must be greater than 0"}]}
== PUT /products {"id":7,"name":"Pen","price":10}
HTTP 200 text/plain;charset=UTF-8
updated
@@ -0,0 +1,11 @@
== POST /old/contact {"email":"[email protected]","message":"This is spam."}
HTTP 400 application/json
{"message":"Message contains 'spam' and must be at least 50 characters long."}
== POST /old/contact {"email":"[email protected]","message":""}
HTTP 500 application/json
{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/old/contact"}
== POST /old/password {"password":"correct-horse","confirmation":"nope"}
HTTP 400 application/json
{}
+11
View File
@@ -0,0 +1,11 @@
== POST /users {"username":"admin","email":"nope","age":15,"roles":["dev"],"address":{"city":"Mumbai","pinCode":"4007"}} [Accept-Language: en]
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"address.pinCode","code":"Pattern","message":"PIN code must be 6 digits"},{"field":"age","code":"Min","message":"Minimum age is 18"},{"field":"email","code":"Email","message":"Enter a work e-mail such as [email protected]"},{"field":"username","code":"AvailableUsername","message":"That username is taken"}]}
== POST /users {"username":"admin","email":"nope","age":15,"roles":["dev"],"address":{"city":"Mumbai","pinCode":"4007"}} [Accept-Language: fr]
HTTP 400 application/problem+json
{"detail":"Invalid request content.","status":400,"title":"Bad Request","errors":[{"field":"address.pinCode","code":"Pattern","message":"Le code postal doit comporter 6 chiffres"},{"field":"age","code":"Min","message":"L'âge minimum est 18"},{"field":"email","code":"Email","message":"Saisissez une adresse professionnelle"},{"field":"username","code":"AvailableUsername","message":"Ce nom d'utilisateur est déjà pris"}]}
== GET /users?size=0&sort=name [Accept-Language: fr]
HTTP 400 application/problem+json
{"detail":"Validation failure","status":400,"title":"Bad Request","errors":[{"field":"size","code":"Min","message":"doit être supérieur ou égal à 1"}]}
+20
View File
@@ -0,0 +1,20 @@
== Spring Boot validator, locale en
age: Minimum age is 18
builtIn: size must be between 3 and 2147483647
el: got 15, need 18
missing: {no.such.key}
other: Resolved from ValidationMessages.properties
== Spring Boot validator, locale fr
age: L'âge minimum est 18
builtIn: la taille doit être comprise entre 3 et 2147483647
el: got 15, need 18
missing: {no.such.key}
other: Resolved from ValidationMessages.properties
== plain Validation.buildDefaultValidatorFactory(), JVM locale en
age: ValidationMessages.properties: minimum age 18
builtIn: size must be between 3 and 2147483647
el: got 15, need 18
missing: {no.such.key}
other: Resolved from ValidationMessages.properties
@@ -0,0 +1,8 @@
== input ${7*7}
code: unknown code: ${7*7}
== input {secret}
code: unknown code: 42
== input {jakarta.validation.constraints.NotNull.message}
code: unknown code: must not be null
+22
View File
@@ -0,0 +1,22 @@
== generated columns of ACCOUNT (H2 information_schema)
AGE INTEGER length=null nullable=NO
ID BIGINT length=null nullable=NO
USERNAME CHARACTER VARYING length=50 nullable=NO
== check constraints on ACCOUNT
"AGE" >= 18
== persist(new Account(null, 15))
jakarta.persistence.RollbackException
age: must be greater than or equal to 18
username: must not be null
rows in ACCOUNT: 0
== load, setAge(10), commit (no save or merge call)
jakarta.persistence.RollbackException
age: must be greater than or equal to 18
== validate a loaded entity whose lazy List<@Valid Note> is untouched
notes initialised before: false
(no violations)
notes initialised after: false
@@ -0,0 +1,4 @@
== MockMvc, no advice, POST /contacts with the short spam message
status: 400
body length: 0
resolved exception: MethodArgumentNotValidException
@@ -0,0 +1 @@
HV000271: Using `@Valid` on a container (java.util.List) is deprecated. You should apply the annotation on the type argument(s). Affected element: ContainerValid#items()
+9
View File
@@ -0,0 +1,9 @@
== with expressly on the classpath
name: need 3 characters, got ab
== without any Jakarta EL implementation
Exception in thread "main" jakarta.validation.ValidationException: HV000183: Unable to initialize 'jakarta.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead
== without EL, using ParameterMessageInterpolator
WARN: HV000185: Message contains EL expression: ${validatedValue}, which is not supported by the selected message interpolator
name: need 3 characters, got ${validatedValue}
+4
View File
@@ -0,0 +1,4 @@
== javac and run
compiled: @Target(FIELD) annotation on a record component
on the record component: []
on the private field: [@RecordTarget.FieldOnly()]
@@ -0,0 +1,7 @@
== POST /contacts {"email":"[email protected]","message":"This is spam."}
HTTP 400 application/problem+json
{"detail":"Invalid request content.","instance":"/contacts","status":400,"title":"Bad Request"}
== GET /users?size=0&sort=name
HTTP 400 application/problem+json
{"detail":"Validation failure","instance":"/users","status":400,"title":"Bad Request"}
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>validation</artifactId>
<version>1.0.0</version>
<name>validation</name>
<description>Bean Validation on Spring Boot 4.2 / Hibernate Validator 9.1: built-in and custom constraints,
groups, method validation, ProblemDetail errors, message i18n, JPA integration and tests.</description>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<!-- Brings hibernate-validator, jakarta.validation-api and an Expression Language implementation. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Only for the JPA integration section. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Duser.language=en -Duser.country=US -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p output target
mvn -B -q dependency:list -DoutputFile=target/deps.txt
grep -E ':(spring-boot|spring-core|hibernate-validator|jakarta\.validation-api|tomcat-embed-el|hibernate-core|junit-jupiter-api):' target/deps.txt \
| sed -E 's/ -- module.*//; s/^ +//' | sort > output/00-versions.txt
java -version 2>&1 | grep -v 'Picked up' | head -1 >> output/00-versions.txt
mvn -B test > target/test.log 2>&1
grep -o "HV000271: .*ContainerValid#items()" target/test.log | head -1 > output/19-container-valid-warning.txt
# Plain Java, with and without an Expression Language implementation
( cd examples/plain-java && mvn -B -q compile dependency:build-classpath -Dmdep.outputFile=target/cp.txt )
FULL="examples/plain-java/target/classes:$(cat examples/plain-java/target/cp.txt)"
NOEL=$(echo "$FULL" | tr ':' '\n' | grep -v -E 'expressly|jakarta\.el' | paste -sd:)
run() { java -Duser.language=en -cp "$1" PlainJava ${2:-} 2>&1 | grep -v -E 'Picked up|HV000001|<clinit>|ParameterMessageInterpolator interpolate' ; }
{
echo "== with expressly on the classpath"
run "$FULL"
echo
echo "== without any Jakarta EL implementation"
run "$NOEL" | grep -m2 -E 'ValidationException|HV000183' || true
echo
echo "== without EL, using ParameterMessageInterpolator"
run "$NOEL" no-el
} > output/20-plain-java.txt
mkdir -p target/record
javac -d target/record examples/record-target/RecordTarget.java 2>&1 | grep -v 'Picked up' || true
{ echo "== javac and run"; java -cp target/record RecordTarget 2>&1 | grep -v 'Picked up'; } > output/21-record-target.txt
# The same ProblemDetail test on the previous minor, to compare the response bodies
OLD=$(mktemp -d)
cp -r pom.xml src "$OLD"/ && mkdir "$OLD/output"
sed -i 's#<version>4.2.0</version>#<version>4.1.3</version>#' "$OLD/pom.xml"
( cd "$OLD" && mvn -B -q test -Dtest=ProblemDetailsPropertyTest > test.log 2>&1 )
cp "$OLD/output/10-http-problemdetails-property.txt" output/22-http-problemdetails-property-on-4.1.3.txt
echo done
@@ -0,0 +1,12 @@
package com.ankurm.validation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ValidationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationDemoApplication.class, args);
}
}
@@ -0,0 +1,27 @@
package com.ankurm.validation.constraint;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.RECORD_COMPONENT;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** A constraint whose validator needs a Spring bean. */
@Documented
@Constraint(validatedBy = AvailableUsernameValidator.class)
@Target({FIELD, PARAMETER, RECORD_COMPONENT})
@Retention(RUNTIME)
public @interface AvailableUsername {
String message() default "{constraints.username.taken}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,24 @@
package com.ankurm.validation.constraint;
import com.ankurm.validation.service.UsernameRegistry;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
/**
* Constructor injection works because Spring Boot's validator creates validators through
* SpringConstraintValidatorFactory. A validator built with plain
* Validation.buildDefaultValidatorFactory() cannot instantiate this class.
*/
public class AvailableUsernameValidator implements ConstraintValidator<AvailableUsername, String> {
private final UsernameRegistry registry;
public AvailableUsernameValidator(UsernameRegistry registry) {
this.registry = registry;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value == null || !registry.isTaken(value);
}
}
@@ -0,0 +1,32 @@
package com.ankurm.validation.constraint;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.RECORD_COMPONENT;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** The smallest custom constraint: a string must be all upper case or all lower case. */
@Documented
@Constraint(validatedBy = CaseCheckValidator.class)
@Target({FIELD, PARAMETER, RECORD_COMPONENT, TYPE_USE})
@Retention(RUNTIME)
public @interface CaseCheck {
String message() default "{constraints.casecheck}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
CaseMode value() default CaseMode.UPPER;
enum CaseMode { UPPER, LOWER }
}
@@ -0,0 +1,26 @@
package com.ankurm.validation.constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Locale;
public class CaseCheckValidator implements ConstraintValidator<CaseCheck, String> {
private CaseCheck.CaseMode mode;
@Override
public void initialize(CaseCheck annotation) {
this.mode = annotation.value();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true; // "is it present?" is @NotNull's job
}
return mode == CaseCheck.CaseMode.UPPER
? value.equals(value.toUpperCase(Locale.ROOT))
: value.equals(value.toLowerCase(Locale.ROOT));
}
}
@@ -0,0 +1,25 @@
package com.ankurm.validation.constraint;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Class-level constraint: end must be after start. */
@Documented
@Constraint(validatedBy = DateRangeValidator.class)
@Target(TYPE)
@Retention(RUNTIME)
public @interface DateRange {
String message() default "{constraints.daterange}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,23 @@
package com.ankurm.validation.constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class DateRangeValidator implements ConstraintValidator<DateRange, HasDateRange> {
@Override
public boolean isValid(HasDateRange value, ConstraintValidatorContext context) {
if (value == null || value.startDate() == null || value.endDate() == null) {
return true; // @NotNull reports the missing date
}
if (value.endDate().isAfter(value.startDate())) {
return true;
}
// Move the error from "the whole object" onto the endDate property.
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode("endDate")
.addConstraintViolation();
return false;
}
}
@@ -0,0 +1,11 @@
package com.ankurm.validation.constraint;
import java.time.LocalDate;
/** Anything with a start and an end date. Records satisfy it with no extra code. */
public interface HasDateRange {
LocalDate startDate();
LocalDate endDate();
}
@@ -0,0 +1,25 @@
package com.ankurm.validation.constraint;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Class-level constraint that does NOT name a property: the violation belongs to the object. */
@Documented
@Constraint(validatedBy = PasswordsMatchValidator.class)
@Target(TYPE)
@Retention(RUNTIME)
public @interface PasswordsMatch {
String message() default "{constraints.passwords.match}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,15 @@
package com.ankurm.validation.constraint;
import com.ankurm.validation.model.PasswordChange;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Objects;
public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, PasswordChange> {
@Override
public boolean isValid(PasswordChange value, ConstraintValidatorContext context) {
return value == null || Objects.equals(value.password(), value.confirmation());
}
}
@@ -0,0 +1,28 @@
package com.ankurm.validation.constraint;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.RECORD_COMPONENT;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = SpamMessageValidator.class)
@Target({FIELD, PARAMETER, RECORD_COMPONENT})
@Retention(RUNTIME)
public @interface SpamMessageCheck {
String message() default "Message contains 'spam' and must be at least {minLength} characters long.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int minLength() default 50;
}
@@ -0,0 +1,27 @@
package com.ankurm.validation.constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Locale;
public class SpamMessageValidator implements ConstraintValidator<SpamMessageCheck, String> {
private int minLength;
@Override
public void initialize(SpamMessageCheck annotation) {
this.minLength = annotation.minLength();
}
@Override
public boolean isValid(String message, ConstraintValidatorContext context) {
if (message == null || message.isBlank()) {
return true; // let @NotBlank report empty messages
}
if (message.toLowerCase(Locale.ROOT).contains("spam")) {
return message.length() >= minLength;
}
return true;
}
}
@@ -0,0 +1,53 @@
package com.ankurm.validation.jpa;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.CascadeType;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Account {
@Id
@GeneratedValue
Long id;
@NotNull
@Size(max = 50)
String username;
@Min(18)
int age;
@OneToMany(mappedBy = "account", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
List<@Valid Note> notes = new ArrayList<>();
protected Account() {
}
public Account(String username, int age) {
this.username = username;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
public Long getId() {
return id;
}
public List<Note> getNotes() {
return notes;
}
}
@@ -0,0 +1,29 @@
package com.ankurm.validation.jpa;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.validation.constraints.NotBlank;
@Entity
public class Note {
@Id
@GeneratedValue
Long id;
@ManyToOne
Account account;
@NotBlank
String text;
protected Note() {
}
public Note(Account account, String text) {
this.account = account;
this.text = text;
}
}
@@ -0,0 +1,9 @@
package com.ankurm.validation.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public record Address(
@NotBlank String city,
@NotBlank @Pattern(regexp = "\\d{6}", message = "{address.pin}") String pinCode) {
}
@@ -0,0 +1,11 @@
package com.ankurm.validation.model;
import com.ankurm.validation.constraint.DateRange;
import com.ankurm.validation.constraint.HasDateRange;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDate;
@DateRange
public record Booking(@NotNull LocalDate startDate, @NotNull LocalDate endDate) implements HasDateRange {
}
@@ -0,0 +1,11 @@
package com.ankurm.validation.model;
import com.ankurm.validation.constraint.SpamMessageCheck;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record ContactForm(
@NotBlank @Email String email,
@NotBlank @Size(min = 10, max = 500) @SpamMessageCheck String message) {
}
@@ -0,0 +1,24 @@
package com.ankurm.validation.model;
import jakarta.validation.GroupSequence;
import jakarta.validation.groups.Default;
/** Groups are just marker interfaces. */
public final class Groups {
public interface OnCreate { }
public interface OnUpdate { }
/** Extending Default means "the update rules plus everything that has no group". */
public interface Update extends Default { }
public interface Expensive { }
/** Check the cheap rules first; only run Expensive if they all pass. */
@GroupSequence({Default.class, Expensive.class})
public interface CheapThenExpensive { }
private Groups() {
}
}
@@ -0,0 +1,8 @@
package com.ankurm.validation.model;
import com.ankurm.validation.constraint.PasswordsMatch;
import jakarta.validation.constraints.Size;
@PasswordsMatch
public record PasswordChange(@Size(min = 8) String password, String confirmation) {
}
@@ -0,0 +1,14 @@
package com.ankurm.validation.model;
import com.ankurm.validation.model.Groups.OnCreate;
import com.ankurm.validation.model.Groups.OnUpdate;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.Positive;
public record ProductRequest(
@Null(groups = OnCreate.class) @NotNull(groups = OnUpdate.class) Long id,
@NotBlank(groups = {OnCreate.class, OnUpdate.class}) String name,
@Positive int price) { // no group = the Default group
}
@@ -0,0 +1,27 @@
package com.ankurm.validation.model;
import com.ankurm.validation.constraint.AvailableUsername;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;
public record UserRequest(
@NotBlank(message = "{user.username.required}")
@Size(min = 3, max = 20, message = "{user.username.size}")
@AvailableUsername
String username,
@NotBlank @Email String email,
@NotNull @Min(value = 18, message = "{user.age.min}") Integer age,
@NotEmpty List<@NotBlank String> roles,
@NotNull @Valid Address address) {
}
@@ -0,0 +1,17 @@
package com.ankurm.validation.service;
import com.ankurm.validation.model.UserRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
/** Parameter constraints belong on the interface, not on the implementation. */
public interface UserService {
String createUser(@NotNull @Valid UserRequest user, @NotBlank String creatorToken);
@NotBlank
String displayName(@NotNull Long id);
String createViaThis(UserRequest user);
}
@@ -0,0 +1,25 @@
package com.ankurm.validation.service;
import com.ankurm.validation.model.UserRequest;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@Service
@Validated // switches method validation on for this bean
public class UserServiceImpl implements UserService {
@Override
public String createUser(UserRequest user, String creatorToken) {
return "created " + user.username();
}
@Override
public String displayName(Long id) {
return id == 0 ? "" : "user-" + id; // id 0 breaks the @NotBlank return-value promise
}
@Override
public String createViaThis(UserRequest user) {
return createUser(user, ""); // self-invocation: never goes through the proxy
}
}
@@ -0,0 +1,17 @@
package com.ankurm.validation.service;
import org.springframework.stereotype.Component;
import java.util.Locale;
import java.util.Set;
/** Stands in for a repository lookup. */
@Component
public class UsernameRegistry {
private static final Set<String> TAKEN = Set.of("admin", "root");
public boolean isTaken(String username) {
return TAKEN.contains(username.toLowerCase(Locale.ROOT));
}
}
@@ -0,0 +1,41 @@
package com.ankurm.validation.web;
import com.ankurm.validation.model.ContactForm;
import com.ankurm.validation.model.PasswordChange;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.stream.Collectors;
/**
* The widely copied BindingResult pattern, kept to show its two bugs:
* toMap() throws on two errors for one field, and getFieldErrors() skips class-level errors.
*/
@RestController
public class BindingResultController {
@PostMapping("/old/contact")
ResponseEntity<?> contact(@Valid @RequestBody ContactForm form, BindingResult result) {
return respond(result);
}
@PostMapping("/old/password")
ResponseEntity<?> password(@Valid @RequestBody PasswordChange change, BindingResult result) {
return respond(result);
}
private ResponseEntity<?> respond(BindingResult result) {
if (result.hasErrors()) {
Map<String, String> errors = result.getFieldErrors().stream()
.collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
return ResponseEntity.badRequest().body(errors);
}
return ResponseEntity.ok("ok");
}
}
@@ -0,0 +1,21 @@
package com.ankurm.validation.web;
import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* The pre-Spring-6.1 habit: class-level @Validated on a controller. It swaps MVC's built-in
* method validation for the AOP proxy, which throws ConstraintViolationException.
*/
@RestController
@Validated
public class LegacyValidatedController {
@GetMapping("/legacy")
String legacy(@RequestParam @Min(1) int size) {
return "size=" + size;
}
}
@@ -0,0 +1,91 @@
package com.ankurm.validation.web;
import com.ankurm.validation.model.Booking;
import com.ankurm.validation.model.ContactForm;
import com.ankurm.validation.model.Groups;
import com.ankurm.validation.model.PasswordChange;
import com.ankurm.validation.model.ProductRequest;
import com.ankurm.validation.model.UserRequest;
import com.ankurm.validation.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.groups.Default;
import org.springframework.validation.annotation.Validated;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** Deliberately NOT annotated with class-level @Validated. */
@RestController
public class UserController {
private final UserService service;
public UserController(UserService service) {
this.service = service;
}
// @Valid on a @RequestBody object -> MethodArgumentNotValidException
@PostMapping("/users")
String create(@Valid @RequestBody UserRequest user) {
return "created " + user.username();
}
// a constraint directly on a parameter -> method validation -> HandlerMethodValidationException
@GetMapping("/users")
String list(@RequestParam @Min(1) @Max(100) int size,
@RequestParam @NotBlank String sort) {
return "size=" + size + " sort=" + sort;
}
@GetMapping("/users/{id}")
String one(@PathVariable @Min(1) long id) {
return service.displayName(id);
}
// a list body: the constraints sit on the element type
@PostMapping("/contacts/bulk")
String bulk(@RequestBody List<@Valid ContactForm> forms) {
return "accepted " + forms.size();
}
@PostMapping("/contacts")
String contact(@Valid @RequestBody ContactForm form) {
return "accepted";
}
@PostMapping("/bookings")
String book(@Valid @RequestBody Booking booking) {
return "booked";
}
@PostMapping("/password")
String password(@Valid @RequestBody PasswordChange change) {
return "changed";
}
// @Valid cannot name a group; Spring's @Validated can
@PostMapping("/products")
String createProduct(@Validated({Default.class, Groups.OnCreate.class}) @RequestBody ProductRequest p) {
return "created";
}
@PutMapping("/products")
String updateProduct(@Validated({Default.class, Groups.OnUpdate.class}) @RequestBody ProductRequest p) {
return "updated";
}
// calls a @Validated service with a bad token: a violation raised below the web layer
@PostMapping("/users/internal")
String internal(@RequestBody UserRequest user) {
return service.createUser(user, "");
}
}
@@ -0,0 +1,101 @@
package com.ankurm.validation.web;
import jakarta.validation.ConstraintViolationException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.method.ParameterErrors;
import org.springframework.validation.method.ParameterValidationResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/** One error shape for all three validation exceptions. Switch off with app.problem-advice=false. */
@RestControllerAdvice
@ConditionalOnBooleanProperty(name = "app.problem-advice", matchIfMissing = true)
public class ValidationProblemAdvice extends ResponseEntityExceptionHandler {
/** field is null for an error that belongs to the whole object. */
public record Violation(String field, String code, String message) { }
private final MessageSource messages;
public ValidationProblemAdvice(MessageSource messages) {
this.messages = messages;
}
// 1. @Valid / @Validated on a single @RequestBody or @ModelAttribute object
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
List<Violation> errors = new ArrayList<>();
ex.getBindingResult().getAllErrors().forEach(e -> errors.add(toViolation(e, request.getLocale())));
return respond(ex, ex.getBody(), errors, headers, status, request);
}
// 2. constraints declared on controller method parameters
@Override
protected ResponseEntity<Object> handleHandlerMethodValidationException(HandlerMethodValidationException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Locale locale = request.getLocale();
List<Violation> errors = new ArrayList<>();
for (ParameterValidationResult result : ex.getParameterValidationResults()) {
if (result instanceof ParameterErrors bean) { // a @Valid object or list element
String prefix = bean.getContainerIndex() != null ? "[" + bean.getContainerIndex() + "]." : "";
bean.getAllErrors().forEach(e -> {
Violation v = toViolation(e, locale);
errors.add(new Violation(prefix + v.field(), v.code(), v.message()));
});
} else { // a simple value such as ?size=0
String name = result.getMethodParameter().getParameterName();
result.getResolvableErrors().forEach(e ->
errors.add(new Violation(name, lastCode(e), messages.getMessage(e, locale))));
}
}
return respond(ex, ex.getBody(), errors, headers, status, request);
}
// 3. a @Validated bean outside the web layer
@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex, WebRequest request) {
List<Violation> errors = new ArrayList<>();
ex.getConstraintViolations().forEach(v -> errors.add(new Violation(
v.getPropertyPath().toString(),
v.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
v.getMessage())));
ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failure");
return respond(ex, body, errors, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
private Violation toViolation(ObjectError error, Locale locale) {
String field = error instanceof FieldError f ? f.getField() : null;
return new Violation(field, error.getCode(), messages.getMessage(error, locale));
}
private static String lastCode(MessageSourceResolvable error) {
String[] codes = error.getCodes();
return codes == null ? null : codes[codes.length - 1];
}
private ResponseEntity<Object> respond(Exception ex, ProblemDetail body, List<Violation> errors,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
errors.sort(Comparator.comparing((Violation v) -> String.valueOf(v.field())).thenComparing(Violation::code));
body.setProperty("errors", errors);
return handleExceptionInternal(ex, body, headers, status, request);
}
}
@@ -0,0 +1,3 @@
# Read by Hibernate Validator itself (works without Spring).
vm.only=Resolved from ValidationMessages.properties
user.age.min=ValidationMessages.properties: minimum age {value}
@@ -0,0 +1,3 @@
spring.application.name=validation
spring.jpa.open-in-view=false
spring.messages.fallback-to-system-locale=false
@@ -0,0 +1,10 @@
user.username.required=Username is required
user.username.size=Username must be between {min} and {max} characters
user.age.min=Minimum age is {value}
address.pin=PIN code must be 6 digits
constraints.casecheck=Wrong letter case
constraints.username.taken=That username is taken
constraints.daterange=End date must be after start date
constraints.passwords.match=Passwords do not match
# Overrides the built-in @Email text for the email field of a userRequest only
Email.userRequest.email=Enter a work e-mail such as [email protected]
@@ -0,0 +1,9 @@
user.username.required=Le nom d'utilisateur est obligatoire
user.username.size=Le nom d'utilisateur doit contenir entre {min} et {max} caractères
user.age.min=L'âge minimum est {value}
address.pin=Le code postal doit comporter 6 chiffres
constraints.casecheck=Casse incorrecte
constraints.username.taken=Ce nom d'utilisateur est déjà pris
constraints.daterange=La date de fin doit suivre la date de début
constraints.passwords.match=Les mots de passe ne correspondent pas
Email.userRequest.email=Saisissez une adresse professionnelle
@@ -0,0 +1,133 @@
package com.ankurm.validation;
import jakarta.validation.UnexpectedTypeException;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.*;
import org.hibernate.validator.constraints.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Every row of the article's cheat sheet is one line of output/01-constraint-cheatsheet.txt. */
class ConstraintCheatSheetTest {
static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
static final Validator VALIDATOR = FACTORY.getValidator();
@AfterAll
static void close() {
FACTORY.close();
}
static class Samples {
@NotNull String notNull;
@Null String isNull;
@NotEmpty String notEmpty;
@NotBlank String notBlank;
@AssertTrue Boolean assertTrue;
@AssertFalse Boolean assertFalse;
@Size(min = 2, max = 4) String size;
@Min(10) Integer min;
@Max(10) Integer max;
@DecimalMin(value = "0.0", inclusive = false) BigDecimal decimalMin;
@DecimalMax("99.99") BigDecimal decimalMax;
@Digits(integer = 3, fraction = 2) BigDecimal digits;
@Positive Integer positive;
@PositiveOrZero Integer positiveOrZero;
@Negative Integer negative;
@NegativeOrZero Integer negativeOrZero;
@Past LocalDate past;
@PastOrPresent LocalDate pastOrPresent;
@Future LocalDate future;
@FutureOrPresent LocalDate futureOrPresent;
@Pattern(regexp = "[A-Z]{3}") String pattern;
@Email String email;
// Hibernate Validator extras (org.hibernate.validator.constraints)
@Length(min = 2, max = 4) String length;
@Range(min = 1, max = 5) Integer range;
@URL String url;
@UUID String uuid;
@CreditCardNumber String creditCard;
@UniqueElements List<String> unique;
@IpAddress String ip;
}
record Probe(String property, Object value) { }
@Test
void cheatSheet() {
Transcript t = new Transcript("01-constraint-cheatsheet");
LocalDate today = LocalDate.now();
List<Probe> probes = List.of(
new Probe("notNull", ""), new Probe("isNull", ""),
new Probe("notEmpty", " "), new Probe("notEmpty", ""),
new Probe("notBlank", " "), new Probe("assertTrue", false), new Probe("assertFalse", true),
new Probe("size", "abcde"), new Probe("min", 9), new Probe("max", 11),
new Probe("decimalMin", new BigDecimal("0.0")), new Probe("decimalMax", new BigDecimal("100")),
new Probe("digits", new BigDecimal("1.234")), new Probe("positive", 0),
new Probe("positiveOrZero", -1), new Probe("negative", 0), new Probe("negativeOrZero", 1),
new Probe("past", today), new Probe("pastOrPresent", today.plusDays(1)),
new Probe("future", today), new Probe("futureOrPresent", today.minusDays(1)),
new Probe("pattern", "ABCD"), new Probe("email", "not-an-email"), new Probe("email", "a@b"),
new Probe("email", ""), new Probe("length", "abcde"), new Probe("range", 6),
new Probe("url", "ankurm.com"), new Probe("uuid", "1234"),
new Probe("creditCard", "4111111111111112"), new Probe("unique", List.of("a", "a")),
new Probe("ip", "999.1.1.1"));
t.head("a sample value for each constraint (property: value -> result)");
for (Probe p : probes) {
var v = VALIDATOR.validateValue(Samples.class, p.property(), p.value());
String shown = p.value() instanceof LocalDate d
? (d.equals(today) ? "today" : d.isAfter(today) ? "tomorrow" : "yesterday")
: p.value() instanceof String s ? "\"" + s + "\"" : String.valueOf(p.value());
String msg = v.isEmpty() ? "valid" : v.iterator().next().getMessage();
t.line(String.format("%-16s %-20s %s", p.property(), shown, msg));
}
t.head("which constraints reject null? (every other field left null)");
var onNull = VALIDATOR.validate(new Samples());
onNull.stream().map(v -> v.getPropertyPath().toString()).sorted()
.forEach(name -> t.line("rejects null: " + name));
t.write();
assertThat(onNull).extracting(v -> v.getPropertyPath().toString())
.containsExactlyInAnyOrder("notNull", "notEmpty", "notBlank");
}
static class Mistake {
@Size(min = 1) Integer quantity = 5;
}
static class NotBlankOnNumber {
@NotBlank Integer quantity = 5;
}
record Pin(@Email(regexp = ".+@.+..+") String loose, @Email(regexp = ".+@.+\\..+") String strict) { }
record Age(@Positive @Min(18) int age) { }
@Test
void mistakes() {
Transcript t = new Transcript("02-constraint-mistakes");
t.head("@Size on an Integer compiles, and fails when first validated");
assertThatThrownBy(() -> VALIDATOR.validate(new Mistake()))
.isInstanceOf(UnexpectedTypeException.class)
.satisfies(e -> t.line(e.getClass().getName()).line(e.getMessage()));
t.head("@NotBlank on an Integer");
assertThatThrownBy(() -> VALIDATOR.validate(new NotBlankOnNumber()))
.satisfies(e -> t.line(e.getMessage()));
t.head("an unescaped dot in @Email(regexp): value a@bcom");
t.line(Transcript.show(VALIDATOR.validate(new Pin("a@bcom", "a@bcom"))));
t.head("@Positive plus @Min(18) on age = -1 reports both");
t.line(Transcript.show(VALIDATOR.validate(new Age(-1))));
t.write();
}
}
@@ -0,0 +1,120 @@
package com.ankurm.validation;
import com.ankurm.validation.constraint.CaseCheck;
import com.ankurm.validation.model.Address;
import com.ankurm.validation.model.Booking;
import com.ankurm.validation.model.ContactForm;
import com.ankurm.validation.model.PasswordChange;
import com.ankurm.validation.model.UserRequest;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
class CustomConstraintTest {
@Autowired
Validator validator; // Spring Boot's auto-configured bean
record Code(@CaseCheck String upper, @CaseCheck(CaseCheck.CaseMode.LOWER) String lower) { }
record Item(@NotBlank String name) { }
record WithValid(@Valid Item item) { }
record WithoutValid(Item item) { }
record ElementValid(List<@Valid Item> items) { }
record ContainerValid(@Valid List<Item> items) { }
/** A composed constraint whose @Target omits RECORD_COMPONENT on purpose. */
@java.lang.annotation.Target(java.lang.annotation.ElementType.FIELD)
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@jakarta.validation.Constraint(validatedBy = {})
@NotBlank
@interface FieldOnlyRequired {
String message() default "required";
Class<?>[] groups() default {};
Class<? extends jakarta.validation.Payload>[] payload() default {};
}
record FieldOnly(@FieldOnlyRequired String name) { }
static UserRequest user(String name, Address address) {
return new UserRequest(name, "[email protected]", 30, List.of("dev"), address);
}
@Test
void customConstraints() {
Transcript t = new Transcript("03-custom-constraints");
t.head("@CaseCheck(UPPER) \"abc\", @CaseCheck(LOWER) \"abc\"");
t.line(Transcript.show(validator.validate(new Code("abc", "abc"))));
t.head("a null value passes the custom rule");
t.line(Transcript.show(validator.validate(new Code(null, null))));
t.head("short spam message");
t.line(Transcript.show(validator.validate(new ContactForm("[email protected]", "This is spam."))));
t.head("long message containing spam");
t.line(Transcript.show(validator.validate(new ContactForm("[email protected]",
"This message mentions spam but is long enough to be taken seriously."))));
t.head("a composed constraint with @Target(FIELD) only, used on a record component");
t.line(Transcript.show(validator.validate(new FieldOnly(" "))));
t.head("validator with a constructor-injected bean, username admin");
t.line(Transcript.show(validator.validate(user("admin", new Address("Mumbai", "400703")))));
t.head("same object, validator built by hand without Spring");
try (var factory = Validation.buildDefaultValidatorFactory()) {
assertThatThrownBy(() -> factory.getValidator().validate(user("admin", new Address("Mumbai", "400703"))))
.isInstanceOf(ValidationException.class)
.satisfies(e -> t.line(e.getClass().getSimpleName() + ": " + e.getMessage()));
}
t.write();
}
@Test
void nesting() {
Transcript t = new Transcript("04-nested-and-containers");
Item bad = new Item("");
t.head("nested object with @Valid");
t.line(Transcript.show(validator.validate(new WithValid(bad))));
t.head("nested object without @Valid");
t.line(Transcript.show(validator.validate(new WithoutValid(bad))));
t.head("List<@Valid Item>");
t.line(Transcript.show(validator.validate(new ElementValid(List.of(new Item("ok"), bad)))));
t.head("@Valid List<Item>");
t.line(Transcript.show(validator.validate(new ContainerValid(List.of(new Item("ok"), bad)))));
t.head("List<@NotBlank String> and a nested record, all wrong");
t.line(Transcript.show(validator.validate(new UserRequest("ravi", "[email protected]", 30,
List.of("dev", " "), new Address("", "4007")))));
t.write();
}
@Test
void crossField() {
Transcript t = new Transcript("05-cross-field");
t.head("@DateRange moves its violation onto endDate");
var range = validator.validate(new Booking(LocalDate.of(2026, 5, 10), LocalDate.of(2026, 5, 1)));
t.line(Transcript.show(range));
t.head("@DateRange with a missing date: only @NotNull speaks");
t.line(Transcript.show(validator.validate(new Booking(LocalDate.of(2026, 5, 10), null))));
t.head("@PasswordsMatch keeps the default object-level violation");
t.line(Transcript.show(validator.validate(new PasswordChange("correct-horse", "wrong-horse"))));
t.head("class-level constraint while a field is also invalid");
t.line(Transcript.show(validator.validate(new PasswordChange("short", "other"))));
t.write();
assertThat(range).extracting(v -> v.getPropertyPath().toString()).containsExactly("endDate");
}
}
@@ -0,0 +1,31 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Booking;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
/** No Spring: the fastest way to test a constraint is through a real Validator. */
class DateRangeValidatorUnitTest {
static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
static final Validator VALIDATOR = FACTORY.getValidator();
@AfterAll
static void close() {
FACTORY.close();
}
@ParameterizedTest
@CsvSource({"2026-05-01, 2026-05-10, 0", "2026-05-10, 2026-05-01, 1", "2026-05-01, 2026-05-01, 1"})
void endMustBeAfterStart(LocalDate start, LocalDate end, int violations) {
assertThat(VALIDATOR.validate(new Booking(start, end))).hasSize(violations);
}
}
@@ -0,0 +1,50 @@
package com.ankurm.validation;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import jakarta.validation.Validation;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/** User input concatenated into a violation template: what gets interpreted? */
class ElInjectionTest {
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Echo.class)
@interface Unknown {
String message() default "unknown";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int secret() default 42;
}
public static class Echo implements ConstraintValidator<Unknown, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("unknown code: " + value).addConstraintViolation();
return false;
}
}
record Input(@Unknown String code) { }
@Test
void userInputInTemplates() {
Transcript t = new Transcript("16-template-injection");
try (var factory = Validation.buildDefaultValidatorFactory()) {
for (String attack : new String[] {"${7*7}", "{secret}", "{jakarta.validation.constraints.NotNull.message}"}) {
t.head("input " + attack);
t.line(Transcript.show(factory.getValidator().validate(new Input(attack))));
}
}
t.write();
}
}
@@ -0,0 +1,58 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Groups.CheapThenExpensive;
import com.ankurm.validation.model.Groups.Expensive;
import com.ankurm.validation.model.Groups.OnCreate;
import com.ankurm.validation.model.Groups.OnUpdate;
import com.ankurm.validation.model.Groups.Update;
import com.ankurm.validation.model.ProductRequest;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.validation.groups.ConvertGroup;
import jakarta.validation.groups.Default;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class GroupsTest {
record Signup(@NotBlank String name, @Size(min = 8, groups = Expensive.class) String password) { }
record Line(@NotNull(groups = OnUpdate.class) Long id) { }
record Plain(@Valid Line line) { }
record Converted(@Valid @ConvertGroup(from = Default.class, to = OnUpdate.class) Line line) { }
@Test
void groups() {
try (var factory = Validation.buildDefaultValidatorFactory()) {
Validator v = factory.getValidator();
Transcript t = new Transcript("06-groups");
ProductRequest bad = new ProductRequest(null, " ", -5);
t.head("new ProductRequest(id=null, name=\" \", price=-5)");
t.line("validate(p) " + Transcript.show(v.validate(bad)));
t.line("validate(p, OnCreate) " + Transcript.show(v.validate(bad, OnCreate.class)));
t.line("validate(p, OnUpdate) " + Transcript.show(v.validate(bad, OnUpdate.class)));
t.line("validate(p, Default, OnUpdate) " + Transcript.show(v.validate(bad, Default.class, OnUpdate.class)));
t.line("validate(p, Update extends Default) " + Transcript.show(v.validate(bad, Update.class)));
t.head("@GroupSequence({Default, Expensive}): name blank, password short");
t.line(Transcript.show(v.validate(new Signup("", "abc"), CheapThenExpensive.class)));
t.head("same sequence once the name is fixed");
t.line(Transcript.show(v.validate(new Signup("ravi", "abc"), CheapThenExpensive.class)));
t.head("cascade: nested rule is in OnUpdate, parent validated with Default");
t.line("@Valid " + Transcript.show(v.validate(new Plain(new Line(null)))));
t.line("@Valid @ConvertGroup " + Transcript.show(v.validate(new Converted(new Line(null)))));
t.write();
assertThat(v.validate(bad, OnCreate.class)).hasSize(1);
assertThat(v.validate(bad)).hasSize(1);
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.validation;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/** Real HTTP against the embedded Tomcat, so error dispatch to /error happens as in production. */
final class Http {
private final HttpClient client = HttpClient.newHttpClient();
private final String base;
private final Transcript t;
Http(int port, Transcript t) {
this.base = "http://localhost:" + port;
this.t = t;
}
int send(String method, String path, String json, String... headers) {
try {
var b = HttpRequest.newBuilder(URI.create(base + path));
b.method(method, json == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json));
if (json != null) {
b.header("Content-Type", "application/json");
}
for (int i = 0; i < headers.length; i += 2) {
b.header(headers[i], headers[i + 1]);
}
var r = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
t.head(method + " " + path + (json == null ? "" : " " + json)
+ (headers.length == 0 ? "" : " [" + headers[0] + ": " + headers[1] + "]"));
t.line("HTTP " + r.statusCode() + " " + r.headers().firstValue("Content-Type").orElse("(no content type)"));
t.line(r.body().isEmpty() ? "(empty body)"
: r.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\""));
return r.statusCode();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,101 @@
package com.ankurm.validation;
import com.ankurm.validation.jpa.Account;
import com.ankurm.validation.jpa.Note;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import org.hibernate.Hibernate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest
class JpaIntegrationTest {
@Autowired
EntityManagerFactory emf;
@Autowired
JdbcTemplate jdbc;
@Autowired
Validator validator;
private void tx(Consumer<EntityManager> work) {
try (EntityManager em = emf.createEntityManager()) {
var tx = em.getTransaction();
tx.begin();
try {
work.accept(em);
tx.commit();
} catch (RuntimeException e) {
if (tx.isActive()) {
tx.rollback();
}
throw e;
}
}
}
private static void report(Transcript t, Throwable e) {
Throwable c = e;
while (c != null && !(c instanceof ConstraintViolationException)) {
c = c.getCause();
}
t.line(e.getClass().getName());
if (c != null) {
((ConstraintViolationException) c).getConstraintViolations().stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage()).sorted().forEach(t::line);
}
}
@Test
void hibernateOrmIntegration() {
Transcript t = new Transcript("17-jpa-integration");
t.head("generated columns of ACCOUNT (H2 information_schema)");
jdbc.queryForList("select column_name, data_type, character_maximum_length, is_nullable "
+ "from information_schema.columns where table_name = 'ACCOUNT' order by column_name")
.forEach(r -> t.line(r.get("column_name") + " " + r.get("data_type") + " length="
+ r.get("character_maximum_length") + " nullable=" + r.get("is_nullable")));
t.head("check constraints on ACCOUNT");
jdbc.queryForList("select cc.check_clause from information_schema.check_constraints cc "
+ "join information_schema.table_constraints tc on tc.constraint_name = cc.constraint_name "
+ "where tc.table_name = 'ACCOUNT' order by 1", String.class)
.forEach(t::line);
t.head("persist(new Account(null, 15))");
Throwable persist = catchThrowable(() -> tx(em -> em.persist(new Account(null, 15))));
report(t, persist);
t.line("rows in ACCOUNT: " + jdbc.queryForObject("select count(*) from account", Integer.class));
long[] id = new long[1];
tx(em -> {
Account a = new Account("ravi", 30);
a.getNotes().add(new Note(a, "first"));
em.persist(a);
em.flush();
id[0] = a.getId();
});
t.head("load, setAge(10), commit (no save or merge call)");
report(t, catchThrowable(() -> tx(em -> em.find(Account.class, id[0]).setAge(10))));
t.head("validate a loaded entity whose lazy List<@Valid Note> is untouched");
tx(em -> {
Account a = em.find(Account.class, id[0]);
t.line("notes initialised before: " + Hibernate.isInitialized(a.getNotes()));
t.line(Transcript.show(validator.validate(a)));
t.line("notes initialised after: " + Hibernate.isInitialized(a.getNotes()));
});
t.write();
assertThat(persist).isNotNull();
}
}
@@ -0,0 +1,46 @@
package com.ankurm.validation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;
@SpringBootTest
class MessagesTest {
record Msg(@Min(value = 18, message = "{user.age.min}") int age,
@Min(value = 18, message = "{vm.only}") int other,
@Min(value = 18, message = "{no.such.key}") int missing,
@Min(value = 18, message = "got ${validatedValue}, need {value}") int el,
@Size(min = 3) String builtIn) { }
@Autowired
Validator springValidator;
@Test
void whereMessagesComeFrom() {
Transcript t = new Transcript("15-message-sources");
Msg bad = new Msg(15, 15, 15, 15, "a");
t.head("Spring Boot validator, locale en");
LocaleContextHolder.setLocale(Locale.ENGLISH);
springValidator.validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
t.head("Spring Boot validator, locale fr");
LocaleContextHolder.setLocale(Locale.FRENCH);
springValidator.validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
LocaleContextHolder.resetLocaleContext();
t.head("plain Validation.buildDefaultValidatorFactory(), JVM locale en");
try (var factory = Validation.buildDefaultValidatorFactory()) {
factory.getValidator().validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
}
t.write();
}
}
@@ -0,0 +1,30 @@
package com.ankurm.validation;
import com.ankurm.validation.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.validation.method.MethodValidationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest(properties = "spring.validation.method.adapt-constraint-violations=true")
class MethodValidationAdaptedTest {
@Autowired
UserService service;
@Test
void adapted() {
Transcript t = new Transcript("08-method-validation-adapted");
t.head("spring.validation.method.adapt-constraint-violations=true, createUser(good, \"\")");
Throwable e = catchThrowable(() -> service.createUser(MethodValidationTest.GOOD, ""));
t.line(e.getClass().getName());
((MethodValidationException) e).getParameterValidationResults().forEach(r ->
r.getResolvableErrors().forEach(err -> t.line(" "
+ r.getMethodParameter().getParameterName() + ": " + err.getDefaultMessage())));
t.write();
assertThat(e).isInstanceOf(MethodValidationException.class);
}
}
@@ -0,0 +1,91 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Address;
import com.ankurm.validation.model.UserRequest;
import com.ankurm.validation.service.UserService;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.constraints.NotNull;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.validation.annotation.Validated;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest
@Import(MethodValidationTest.Extra.class)
class MethodValidationTest {
interface Greeter {
String greet(String name);
}
/** Adds a parameter constraint the interface does not declare. Not allowed. */
@Validated
static class StricterGreeter implements Greeter {
@Override
public String greet(@NotNull String name) {
return "hi " + name;
}
}
@TestConfiguration
static class Extra {
@Bean
Greeter greeter() {
return new StricterGreeter();
}
}
@Autowired
UserService service;
@Autowired
Greeter greeter;
static final UserRequest GOOD = new UserRequest("ravi", "[email protected]", 30, List.of("dev"),
new Address("Mumbai", "400703"));
static void report(Transcript t, ThrowingCallable call) {
Throwable e = catchThrowable(call);
if (e == null) {
t.line("no exception");
return;
}
t.line(e.getClass().getName());
if (e instanceof ConstraintViolationException cve) {
cve.getConstraintViolations().stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
} else {
t.line(" " + e.getMessage().lines().findFirst().orElse(""));
}
}
@Test
void methodValidation() {
Transcript t = new Transcript("07-method-validation");
t.line("service is an AOP proxy: " + AopUtils.isAopProxy(service));
t.head("createUser(good, \"\")");
report(t, () -> service.createUser(GOOD, ""));
t.head("createUser(null, \"token\")");
report(t, () -> service.createUser(null, "token"));
t.head("displayName(0) - the RETURN value is invalid");
report(t, () -> service.displayName(0L));
t.head("createViaThis(good) - calls createUser(user, \"\") on this");
report(t, () -> t.line("returned: " + service.createViaThis(GOOD)));
t.head("implementation adds @NotNull that the interface lacks");
report(t, () -> greeter.greet("x"));
t.write();
assertThat(catchThrowable(() -> service.createUser(GOOD, "")))
.isInstanceOf(ConstraintViolationException.class);
}
}
@@ -0,0 +1,33 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import static org.assertj.core.api.Assertions.assertThat;
/** The same default request as in 09-http-defaults, through MockMvc: no servlet error dispatch. */
@SpringBootTest(properties = "app.problem-advice=false")
@AutoConfigureMockMvc
class MockMvcEmptyBodyTest {
@Autowired
MockMvcTester mvc;
@Test
void bodyIsEmptyInMockMvc() throws Exception {
var result = mvc.post().uri("/contacts").contentType(MediaType.APPLICATION_JSON)
.content(WebDefaultsTest.SPAM).exchange();
String body = result.getResponse().getContentAsString();
Transcript t = new Transcript("18-mockmvc-vs-server");
t.head("MockMvc, no advice, POST /contacts with the short spam message");
t.line("status: " + result.getResponse().getStatus());
t.line("body length: " + body.length());
t.line("resolved exception: " + result.getMvcResult().getResolvedException().getClass().getSimpleName());
t.write();
assertThat(body).isEmpty();
}
}
@@ -0,0 +1,59 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProblemAdviceTest {
static final String BAD_USER = "{\"username\":\"admin\",\"email\":\"nope\",\"age\":15,\"roles\":[\"dev\"],"
+ "\"address\":{\"city\":\"Mumbai\",\"pinCode\":\"4007\"}}";
@LocalServerPort
int port;
@Test
void oneShapeForEveryFailure() {
Transcript t = new Transcript("11-http-problem-advice");
Http http = new Http(port, t);
http.send("POST", "/users", BAD_USER);
http.send("GET", "/users?size=0&sort=name", null);
http.send("POST", "/contacts/bulk", "[{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}]");
http.send("POST", "/password", "{\"password\":\"correct-horse\",\"confirmation\":\"nope\"}");
http.send("POST", "/users/internal", "{}");
http.send("POST", "/bookings", "{\"startDate\":\"2026-05-10\",\"endDate\":\"2026-05-01\"}");
http.send("POST", "/bookings", "{\"startDate\":\"10/05/2026\"}");
t.write();
}
@Test
void groupsOverHttp() {
Transcript t = new Transcript("12-http-groups");
Http http = new Http(port, t);
http.send("POST", "/products", "{\"id\":7,\"name\":\"Pen\",\"price\":10}");
http.send("PUT", "/products", "{\"name\":\"Pen\",\"price\":-1}");
http.send("PUT", "/products", "{\"id\":7,\"name\":\"Pen\",\"price\":10}");
t.write();
}
@Test
void bindingResultPattern() {
Transcript t = new Transcript("13-http-bindingresult-pitfalls");
Http http = new Http(port, t);
http.send("POST", "/old/contact", "{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}");
http.send("POST", "/old/contact", "{\"email\":\"[email protected]\",\"message\":\"\"}");
http.send("POST", "/old/password", "{\"password\":\"correct-horse\",\"confirmation\":\"nope\"}");
t.write();
}
@Test
void localised() {
Transcript t = new Transcript("14-http-i18n");
Http http = new Http(port, t);
http.send("POST", "/users", BAD_USER, "Accept-Language", "en");
http.send("POST", "/users", BAD_USER, "Accept-Language", "fr");
http.send("GET", "/users?size=0&sort=name", null, "Accept-Language", "fr");
t.write();
}
}
@@ -0,0 +1,22 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"app.problem-advice=false", "spring.mvc.problemdetails.enabled=true"})
class ProblemDetailsPropertyTest {
@LocalServerPort
int port;
@Test
void propertyOnly() {
Transcript t = new Transcript("10-http-problemdetails-property");
Http http = new Http(port, t);
http.send("POST", "/contacts", WebDefaultsTest.SPAM);
http.send("GET", "/users?size=0&sort=name", null);
t.write();
}
}
@@ -0,0 +1,54 @@
package com.ankurm.validation;
import jakarta.validation.ConstraintViolation;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
/** Collects the lines a test observed and writes them to output/NN-name.txt. */
final class Transcript {
private final Path file;
private final StringBuilder text = new StringBuilder();
Transcript(String name) {
this.file = Path.of("output", name + ".txt");
}
Transcript line(String s) {
text.append(s).append('\n');
return this;
}
Transcript head(String s) {
if (!text.isEmpty()) {
text.append('\n');
}
return line("== " + s);
}
void write() {
try {
Files.createDirectories(file.getParent());
Files.writeString(file, text.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Violations as "path: message" in a stable order. */
static <T> String show(Set<ConstraintViolation<T>> violations) {
if (violations.isEmpty()) {
return "(no violations)";
}
return violations.stream()
.map(v -> (v.getPropertyPath().toString().isEmpty() ? "<object>" : v.getPropertyPath().toString())
+ ": " + v.getMessage())
.sorted()
.reduce((a, b) -> a + " | " + b)
.orElseThrow();
}
}
@@ -0,0 +1,50 @@
package com.ankurm.validation;
import com.ankurm.validation.constraint.AvailableUsernameValidator;
import com.ankurm.validation.service.UserService;
import com.ankurm.validation.service.UsernameRegistry;
import com.ankurm.validation.web.UserController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/** A web slice: real controller, real validator, real advice, mocked collaborators. */
@WebMvcTest(UserController.class)
class ValidationSliceTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
UserService service;
@MockitoBean
UsernameRegistry registry; // the custom validator's dependency
@Test
void takenUsernameIsReportedOnTheUsernameField() {
given(registry.isTaken("ravi")).willReturn(true);
assertThat(mvc.post().uri("/users").contentType(MediaType.APPLICATION_JSON).content("""
{"username":"ravi","email":"[email protected]","age":30,"roles":["dev"],
"address":{"city":"Mumbai","pinCode":"400703"}}
"""))
.hasStatus(400)
.bodyJson()
.extractingPath("$.errors[0].code").isEqualTo("AvailableUsername");
}
@Test
void parameterConstraintIsEnforcedInTheSliceToo() {
assertThat(mvc.get().uri("/users?size=500&sort=name"))
.hasStatus(400)
.bodyJson()
.extractingPath("$.errors[0].field").isEqualTo("size");
}
}
@@ -0,0 +1,32 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
/** What you get with no @RestControllerAdvice of your own. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "app.problem-advice=false")
class WebDefaultsTest {
static final String SPAM = "{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}";
@LocalServerPort
int port;
@Test
void bare() {
Transcript t = new Transcript("09-http-defaults");
Http http = new Http(port, t);
int body = http.send("POST", "/contacts", SPAM);
int param = http.send("GET", "/users?size=0&sort=name", null);
int list = http.send("POST", "/contacts/bulk", "[" + SPAM + "]");
int legacy = http.send("GET", "/legacy?size=0", null);
int service = http.send("POST", "/users/internal", "{}");
t.write();
assertThat(new int[] {body, param, list}).containsOnly(400);
assertThat(new int[] {legacy, service}).containsOnly(500);
}
}