Sub topic 9
Writing a custom constraint
This chapter assumes you know the standard constraint annotations such as @NotBlank and @Size, and that you trigger validation with @Valid on a request body. When no standard annotation expresses a rule, you can write your own.
Why a custom constraint
Standard annotations cover generic rules: not null, size, range, pattern. Business rules are different, for example "the country must be one we ship to". You could put that check in the controller. A custom constraint is better because the rule is declared on the field, reused across DTOs, and reported through the same error handling as every other violation.
A custom constraint has two parts:
- An annotation that marks the field.
- A
ConstraintValidatorclass that decides whether a value is valid.
The annotation
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 is not supported";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Bean Validation requires these pieces:
@Constraint(validatedBy = ...)links the annotation to its validator.@Retention(RUNTIME)lets the framework read the annotation while the application runs. Without it, the rule is silently ignored.@Targetlists where the annotation may appear.RECORD_COMPONENTis needed to use it on record components.message,groupsandpayloadare mandatory attributes. A constraint missing any of them fails when the validator is first built.
The validator
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Set;
class AllowedCountryValidator implements ConstraintValidator<AllowedCountry, String> {
private static final Set<String> SUPPORTED = Set.of("DE", "FR", "US");
@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 checks. Here the constraint applies only to String. Putting it on an Integer fails at validation time with an error saying no validator could be found.
isValid returns true for null. This is the convention for every standard constraint. It keeps each rule to one job: @AllowedCountry checks the value, and @NotNull or @NotBlank checks presence. If you want the field required, combine them.
Using it
import jakarta.validation.constraints.NotBlank;
public record AddressRequest(
@NotBlank String street,
@NotBlank @AllowedCountry String country) {
}With @Valid @RequestBody AddressRequest request on the controller method, a request with "country": "BR" returns 400. The MethodArgumentNotValidException handler from the earlier chapter then reports country is not supported under the country key.
Dependencies in validators
Spring creates validator instances through its own factory, so a validator can take constructor-injected beans. This allows a rule such as "the country exists in a configuration table". Keep these checks cheap and free of side effects, because validation runs on every request. Uniqueness checks against a database also race with concurrent requests, so the database constraint must remain the final guard.
Common errors
| Symptom | Likely cause |
|---|---|
| The constraint never fires | Missing `@Retention(RUNTIME)`, or the parameter lacks `@Valid` |
| Error about a missing `groups` or `payload` method | Required attribute omitted from the annotation |
| "No validator could be found for type" | The `ConstraintValidator` type argument does not match the field type |
| `null` input is rejected unexpectedly | `isValid` returns `false` for `null` |
Exercise
Write the isValid body for a validator that accepts only strings of exactly five digits, such as a postal code, while still treating null as valid. Why return true for null?
Show answer
return value == null || value.matches("\\d{5}"); Null is treated as valid so the constraint checks only the format. Whether the field is required is a separate rule, expressed with @NotNull or @NotBlank, so the two can be combined or used independently.