java-request-validation
Java Request Validation
Inspect And Reuse The Input Boundary
Inspect the installed Java/Spring version, serializers, binding/coercion settings, validation provider, controller signatures, error handlers, and submission contract. Reuse them. Preserve published unknown-field, media-type, error-collection, normalization, and compatibility behavior unless changing it is requested. Do not introduce a reflection hydrator, DTO registry, servlet filter, or custom argument resolver when framework binding already satisfies the requirement.
Validation Ownership
- Validate external request shape at the entry boundary: required values, nullability, types, lengths, formats, supported values, and input-only cross-field rules. For MVC JSON bodies, prefer typed
@RequestBodyplus Bean Validation with@Validor the project's validation groups. - Do not repeat already-validated request syntax in services or repositories. Other actual entry points such as imports, jobs, and CLI adapters validate their external data at their own boundary. Do not add service checks for hypothetical callers.
- Preserve domain invariants required for every caller. Uniqueness, ownership, permissions and lifecycle transitions need the operation's current state and, where appropriate, transactional/database enforcement; DTO validation alone is insufficient.
- Treat hydration/binding, constraint execution, and HTTP error mapping as different responsibilities without requiring a separate class for every phase. Use cohesive local operations under
java-readable-codeand narrow exception ownership underjava-logging-exceptions.
DTOs And Binding
Define required/optional fields, raw types, nested objects, collections and extra-field policy. Where absence and explicit null differ, represent presence intentionally; a plain nullable Java field or primitive alone cannot preserve that distinction. Verify the real parser's number, enum, boolean, and scalar coercion behavior instead of assuming DTO types reject all invalid JSON.
Prefer immutable input DTOs where the installed Java/framework supports them. Apply constraints to input contracts; use built-in constraints before a custom side-effect-free validator. Presence constraints and format constraints are distinct. Cascade nested object validation and validate collection elements where needed; @Valid does not construct nested objects, require non-null input, or define element types by itself.