Building Custom Constraint Annotations
Create reusable custom validators with ConstraintValidator for domain-specific validation logic.
Why Custom Constraints?
Bean Validation ships with annotations like @NotNull, @Size, and @Email. But real applications have domain-specific rules that no built-in annotation covers.
- A username must be lowercase and 3-20 chars
- A phone number must match your country's format
- A status field must be one of an allowed enum set
Instead of writing manual checks in every controller or service, you can build a reusable custom constraint annotation that plugs into the same validation pipeline as the built-in ones.
The Two Pieces of a Custom Constraint
Every custom constraint in Spring Boot 4 (which uses Jakarta Bean Validation) has exactly two parts:
- The annotation — what you write on a field, e.g.
@ValidUsername. It declares metadata and points to a validator. - The ConstraintValidator — a class containing the actual
isValid()logic.
The @Constraint meta-annotation links the two together. When validation runs, the framework instantiates your validator and calls isValid() for each annotated field.
All lessons in this course
- Bean Validation Constraints and Constraint Groups
- Building Custom Constraint Annotations
- Global Exception Handling with @ControllerAdvice
- RFC 7807 Problem Detail Responses