Input validation & custom validators
Bean Validation (Jakarta), @Valid, groups, writing your own constraint like @StrongPassword or @SafeText, and the layers of validation a real system needs.
The concept
Never trust input. Jakarta Bean Validation (implemented by Hibernate Validator) lets you declare rules as annotations:
public record RegisterUserRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email,
@NotBlank @Size(min = 12, max = 128) String password,
@Pattern(regexp = "^\\+?[0-9]{10,15}$") String phone) {}
@PostMapping("/users")
ResponseEntity<UserResponse> register(@Valid @RequestBody RegisterUserRequest req) { /* ... */ }
When validation fails, Spring throws MethodArgumentNotValidException before your method runs, and your @ControllerAdvice turns it into a 400 with field errors.
Common constraints: @NotNull, @NotBlank, @NotEmpty, @Size, @Min/@Max, @Positive, @DecimalMin, @Email, @Pattern, @Past/@Future.
For @PathVariable / @RequestParam, annotate the controller with @Validated; violations then surface as ConstraintViolationException.
Writing a custom constraint
@Target({FIELD, PARAMETER}) @Retention(RUNTIME)
@Constraint(validatedBy = StrongPasswordValidator.class)
public @interface StrongPassword {
String message() default "Password must contain upper, lower, digit and symbol";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class StrongPasswordValidator implements ConstraintValidator<StrongPassword, String> {
public boolean isValid(String v, ConstraintValidatorContext ctx) {
if (v == null) return true; // let @NotNull handle null
return v.length() >= 12 && v.chars().anyMatch(Character::isUpperCase)
&& v.chars().anyMatch(Character::isLowerCase) && v.chars().anyMatch(Character::isDigit)
&& v.chars().anyMatch(c -> !Character.isLetterOrDigit(c));
}
}
In your projects
validation/Lowercase.java · LowercaseValidator.java@Lowercase ensures emails arrive in lowercase. It is a small first custom constraint, alongside @NotBlank, @Email and @Size on RegisterUserRequest.
shared/validation/StrongPassword.java@StrongPassword and its validator, plus @Pattern on CreateBookingRequest for academic year and semester formats.
shared/validation/*Security-oriented constraints: @NoHtml (rejects markup in text fields), @SafeUsername and @StrongPassword.
shared/validation/SafeText.java · SafeTextValidator@SafeText rejects < and > in free-text fields. SperoTek also enforces deeper rules in its services: PasswordPolicy (12 characters minimum, history of 5), breach checking with HIBP, and JournalRules.check(...) for accounting invariants.
The layers of validation
| Layer | Example | Catches |
|---|---|---|
| 1. Syntax (Bean Validation) | @Email, @Size |
Malformed input |
| 2. Business rules (service) | “booking must be in an open semester”, “journal must balance” | Valid shape, invalid meaning |
| 3. Database constraints | CHECK (current_occupancy <= capacity), UNIQUE |
Races and bugs that slip past 1 and 2 |
Layer 3 is the last line of defence. Two concurrent requests can both pass the service check, and only the database can stop the second one. See the constraints lesson.
Alternatives
- Manual
ifchecks: flexible, but scattered and inconsistent error messages. - Validation groups:
@NotNull(groups = OnCreate.class)varies the rules per operation (an alternative to separate Create/Update DTOs). - Validating in the domain: a compact record constructor or entity factory (
Booking.createBooking(...)) guarantees invariants no matter who calls it.
Related concepts you must know
- Allow-lists vs block-lists.
@SafeTextblocks<>, while@Pattern("[a-z0-9_]+")allows only known-good characters. Allow-lists are stronger. - Normalisation. Trim and lowercase before uniqueness checks, otherwise “A@x.com” and “a@x.com” become two accounts.
- Input validation is not output encoding. XSS is really prevented by escaping on render (Module 4).
- Request size limits. IR3D caps multipart uploads at 25 MB.