Sub topic 12
Cross-field rules with class-level constraints
This chapter assumes you can declare field constraints on a DTO, trigger them with @Valid, and return errors from a @RestControllerAdvice. Those steps are covered in the earlier chapters.
Why field constraints are not enough
Annotations such as @NotNull and @Min look at one value. Some rules compare several values. Examples are "the end date is after the start date" and "password and confirmation match". A constraint on one field cannot see the other field, so you put the constraint on the class instead.
A class-level constraint is an annotation with @Target(ElementType.TYPE). Its ConstraintValidator receives the whole object, so it can read any component.
The constraint annotation and validator
The annotation has the usual three attributes: message, groups, and payload. The validator is typed to the DTO.
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
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.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidDateRangeValidator.class)
public @interface ValidDateRange {
String message() default "endDate must be after startDate";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
class ValidDateRangeValidator implements ConstraintValidator<ValidDateRange, BookingRequest> {
@Override
public boolean isValid(BookingRequest value, ConstraintValidatorContext context) {
if (value == null || value.startDate() == null || value.endDate() == null) {
return true;
}
if (value.endDate().isAfter(value.startDate())) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode("endDate")
.addConstraintViolation();
return false;
}
}The validator returns true when either date is null. This follows the same convention as other custom constraints: @NotNull reports the missing value, and this rule only runs when both values exist. Without that check you would report two errors for one mistake.
Applying it to the DTO
Place the annotation on the record itself.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDate;
@ValidDateRange
public record BookingRequest(
@NotBlank String guest,
@NotNull LocalDate startDate,
@NotNull LocalDate endDate) {
}A controller method with @Valid @RequestBody BookingRequest request now checks the field constraints and the date rule in the same validation pass.
Choosing where the error is reported
By default a class-level violation is attached to the object, not to a field. Spring records it as a global error (ObjectError). The handler from the error-handling chapter reads only getFieldErrors(), so it would silently drop this message. The response would be a 400 with no explanation.
The validator above avoids this. It calls disableDefaultConstraintViolation() and then rebuilds the violation with addPropertyNode("endDate"). Spring now reports a field error on endDate, and the existing handler includes it.
If you prefer to keep object-level errors, extend the handler to also read ex.getBindingResult().getGlobalErrors(). Use a key such as "_global" for them.
Common mistakes
- Reading fields from a validator typed to
Object, then casting. Type the validator to the DTO, or to a shared interface if several DTOs need the rule. - Forgetting the null guards, which causes a
NullPointerExceptionor duplicate messages. - Expecting the error to appear under a field name without adding a property node.
- Putting the annotation on a field instead of the type. It then receives only that field's value.
Exercise
A class-level constraint rejects a request, but the JSON response from your handler has an empty "errors" map. The handler uses getFieldErrors(). What is the cause, and what are two ways to fix it?
Show answer
The violation is a global (object-level) error, so getFieldErrors() does not return it. Fix it either by adding a property node in the validator (disableDefaultConstraintViolation(), then buildConstraintViolationWithTemplate(...).addPropertyNode("field").addConstraintViolation()), or by also reading getGlobalErrors() in the handler.