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
+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"}