Sub topic 9
Writing a custom constraint
This chapter assumes you have a request DTO with standard constraints, a controller that uses @Valid, and a @RestControllerAdvice that returns 400 responses. It covers the annotation, the validator class, parameters, custom messages, Spring integration, and the mistakes that most often make a custom constraint fail silently.
When a custom constraint is worth it
The standard annotations such as @NotBlank, @Size and @Pattern cover most field checks. Write your own constraint when:
- The rule has a name in your domain, such as "supported country" or "valid IBAN", and you want to reuse it across DTOs.
- The rule needs logic that a regular expression cannot express cleanly.
- The rule needs a Spring bean, for example a lookup against configuration.
For a rule used once, a check in the service layer is often simpler. A constraint pays off when several DTOs share it.
The two parts of a constraint
A custom constraint has two parts. The annotation declares the rule and its attributes. A class that implements ConstraintValidator decides whether a value passes.
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AllowedCountryValidator.class)
public @interface AllowedCountry {
String message() default "country must be one of {value}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] value() default {"DE", "FR", "US"};
}Every constraint annotation must declare message, groups and payload with these exact types. If one is missing, Hibernate Validator throws a ConstraintDefinitionException when it first inspects the class. The extra value attribute is ours. It makes the allowed set configurable at each use site.
The annotation needs RetentionPolicy.RUNTIME. Without it the validator never sees the annotation, and the constraint is ignored with no error.
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Set;
public class AllowedCountryValidator implements ConstraintValidator<AllowedCountry, String> {
private Set<String> supported = Set.of();
@Override
public void initialize(AllowedCountry annotation) {
supported = Set.copyOf(Arrays.asList(annotation.value()));
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value == null || supported.contains(value);
}
}The two type arguments are the annotation type and the type of value it can validate. initialize runs once for each place the annotation is used. It is the place to copy attribute values into fields. isValid runs for every validation and returns true when the value passes.
Using it looks like any other constraint:
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public record ShippingRequest(
@NotBlank String recipient,
@NotNull @AllowedCountry({"DE", "FR"}) String country) {
}How the pieces run
The diagram shows when each part is called during a request.
The custom constraint needs no extra handler. Its violation arrives as a FieldError inside MethodArgumentNotValidException, so the advice from the earlier chapter already formats it.
Null handling
isValid above returns true for null. This is the Bean Validation convention. It keeps each constraint to one job: @AllowedCountry checks the value only when there is one, and @NotNull decides whether a value is required. A field with only @AllowedCountry accepts a missing country. A field that must be present and supported needs both annotations.
If your validator rejects null, users get confusing errors on optional fields, and @NotNull plus your constraint can report the same problem twice.
Choosing the validated type
ConstraintValidator<A, T> applies only to values of type T. If you put @AllowedCountry on an Integer field, Hibernate Validator finds no matching validator and throws UnexpectedTypeException at validation time, not at startup. To support several types, list several validators:
@Constraint(validatedBy = {AllowedCountryValidator.class, AllowedCountryCodeValidator.class})Hibernate Validator picks the validator whose type matches the annotated value.
Controlling the message
A violation message can contain placeholders. {value} is replaced by the annotation attribute of that name, so @AllowedCountry({"DE", "FR"}) produces country must be one of [DE, FR]. Placeholders in braces use the message interpolator. Text in ${...} is evaluated as an expression.
You can replace the default violation from inside isValid, for example to give different reasons for different failures:
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if (!value.equals(value.toUpperCase())) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("country code must be upper case")
.addConstraintViolation();
return false;
}
return supported.contains(value);
}Using Spring beans in a validator
When Spring Boot creates the Validator, it uses a constraint validator factory that builds validator classes as Spring-managed instances. A validator can take dependencies through its constructor:
- Declare a constructor that accepts the bean, for example a
CountryPropertiesconfiguration class. - Keep the validator class public, with no state that changes between calls.
This works only when Spring creates the validator. A plain Validation.buildDefaultValidatorFactory() has no Spring context and needs a no-argument constructor.
A validator that queries a database, such as "email is not already registered", is allowed. Treat it as a friendly early error, not a guarantee. Two concurrent requests can both pass the check. A unique index in the database remains the real protection.
Validator instances may be reused across threads, so do not store per-request data in fields. Setting fields in initialize is safe because it runs before the instance is used.
Testing the constraint
A plain Validator test needs no Spring context and runs fast. The validation starter supplies Hibernate Validator and the expression language support it needs.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.util.Set;
import org.junit.jupiter.api.Test;
class AllowedCountryTest {
record Address(@AllowedCountry String country) {
}
private final Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
@Test
void rejectsUnsupportedCountry() {
Set<ConstraintViolation<Address>> violations = validator.validate(new Address("JP"));
assertEquals(1, violations.size());
assertEquals("country", violations.iterator().next().getPropertyPath().toString());
}
@Test
void acceptsSupportedCountryAndNull() {
assertTrue(validator.validate(new Address("DE")).isEmpty());
assertTrue(validator.validate(new Address(null)).isEmpty());
}
}Testing null explicitly guards the convention described above.
Common errors
| Symptom | Likely cause |
|---|---|
| Constraint never fires | Annotation lacks `@Retention(RetentionPolicy.RUNTIME)`, or the DTO parameter lacks `@Valid` |
| `ConstraintDefinitionException` | `message`, `groups` or `payload` is missing or has the wrong type |
| `UnexpectedTypeException` | No `ConstraintValidator` matches the annotated type |
| `null` field fails with a confusing error | `isValid` returns `false` for `null` |
| Validator bean is `null` or construction fails | The validator was created outside Spring, or it has no usable constructor |
Exercise
A teammate writes @AllowedCountry on an optional country field. A request omits the field, and validation passes. They call this a bug. What is your answer, and how do they make the field required?
Show answer
It is intended behavior. By convention a validator returns true for null so each constraint has one job. To make the field required, add @NotNull (or @NotBlank for strings) next to @AllowedCountry.
Exercise
You add @AllowedCountry to an Integer field named countryId. What happens, and when?
Show answer
Hibernate Validator finds no ConstraintValidator for Integer and throws UnexpectedTypeException when that object is validated at runtime, not at application startup. Fix it by applying the constraint to a String, or by registering a second validator class that handles Integer in validatedBy.