Sub topic 12
Cross-field rules with class-level constraints
This chapter assumes you can write a request DTO with standard constraints and trigger validation with @Valid on a @RequestBody. It also assumes you have a @RestControllerAdvice that handles MethodArgumentNotValidException, and that you have seen the basic custom constraint (annotation plus ConstraintValidator). Here you will extend that pattern to rules that involve more than one field.
Why field constraints are not enough
A field constraint such as @NotBlank sees one value. It cannot answer questions like these:
- Does
confirmPasswordequalpassword? - Is
endDateafterstartDate? - If
shippingMethodisPICKUP, isaddressallowed to be empty?
Each of these compares or combines fields. Bean Validation handles them with a class-level constraint, which is a constraint annotation placed on the type instead of on a field. Its validator receives the whole object, so it can read every field.
The structure of a class-level constraint
A class-level constraint has the same parts as a field-level custom constraint, with two differences:
- The annotation targets
ElementType.TYPE. - The validator's second type parameter is the DTO type, not a field type like
String.
The first snippet is the annotation. It goes in its own file, PasswordsMatch.java.
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.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordsMatchValidator.class)
public @interface PasswordsMatch {
String message() default "passwords do not match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}The message, groups and payload members are required by the Bean Validation specification for every constraint. If you leave any of them out, the provider rejects the annotation when it first validates a class that uses it.
The DTO carries the annotation on the record itself, not on a component. This goes in RegisterRequest.java.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@PasswordsMatch
public record RegisterRequest(
@NotBlank @Email String email,
@NotBlank @Size(min = 8, max = 72) String password,
@NotBlank String confirmPassword) {
}Writing the validator
The validator is a plain class, so you can compare fields with ordinary Java. This goes in PasswordsMatchValidator.java.
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class PasswordsMatchValidator
implements ConstraintValidator<PasswordsMatch, RegisterRequest> {
@Override
public boolean isValid(RegisterRequest value, ConstraintValidatorContext context) {
if (value == null || value.password() == null || value.confirmPassword() == null) {
return true;
}
if (value.password().equals(value.confirmPassword())) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
context.getDefaultConstraintMessageTemplate())
.addPropertyNode("confirmPassword")
.addConstraintViolation();
return false;
}
}Three details in this validator matter.
Treat missing values as valid
Bean Validation does not stop at the first failure. It runs the field constraints and the class-level constraint in the same pass. If password is null, @NotBlank reports it, and your class-level validator also runs and sees the null. If the validator dereferenced it, you would get a NullPointerException instead of a 400 response. Returning true for missing values leaves "is it present" to @NotBlank and @NotNull, which keeps each rule in one place.
Attach the violation to a field
By default, a failed class-level constraint produces a violation whose property path is empty, because it belongs to the object as a whole. The code above removes the default violation and builds a new one on the confirmPassword node. This makes the error appear next to the field the user must fix.
getDefaultConstraintMessageTemplate() returns the raw message value from the annotation. Passing it to buildConstraintViolationWithTemplate keeps message interpolation and externalized messages working. If you pass a hard-coded string instead, the violation no longer follows the annotation's message attribute.
Do not disable the default violation unless you add another
disableDefaultConstraintViolation() removes the standard violation. If you call it and never call addConstraintViolation(), the validator returns false but reports no violation, and the request passes. Always pair the two.
Where the error ends up
The way Spring MVC records a violation depends on its property path. This decides whether your existing exception handler sees it.
| Violation property path | Stored in the binding result as | Read with |
|---|---|---|
| `confirmPassword` (property node added) | `FieldError` | `getFieldErrors()` |
| empty (no node added) | `ObjectError` | `getGlobalErrors()` |
The handler from the earlier chapter loops over getFieldErrors() only. A class-level violation without a property node would be dropped from the response, and the client would get a 400 with an empty errors object. If you use both styles, read both lists.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
problem.setProperty("errors", errors);
List<String> globalErrors = ex.getBindingResult().getGlobalErrors().stream()
.map(ObjectError::getDefaultMessage)
.toList();
if (!globalErrors.isEmpty()) {
problem.setProperty("globalErrors", globalErrors);
}
return problem;
}
}With a mismatched password, the response body contains "errors": {"confirmPassword": "passwords do not match"}. A rule that involves the whole object, such as "at least one contact method is required", fits better as a global error with no property node.
How the pieces run together
The diagram shows one validation pass over a request body.
A lighter option: @AssertTrue on a method
For a simple rule used in one DTO, a full annotation and validator is a lot of code. Bean Validation also validates boolean getter-style methods annotated with @AssertTrue. The method name must start with is so that it counts as a property.
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDate;
public record BookingRequest(
@NotNull LocalDate checkIn,
@NotNull LocalDate checkOut) {
@JsonIgnore
@AssertTrue(message = "checkOut must be after checkIn")
public boolean isDateRangeValid() {
return checkIn == null || checkOut == null || checkOut.isAfter(checkIn);
}
}The violation's property path is dateRangeValid, which is the name of the derived property. That name is meaningless to a client, so you usually map it or accept it as a global-style message. @JsonIgnore keeps Jackson from treating the method as part of the JSON shape.
Choosing between the approaches
| Approach | Reusable across DTOs | Controls the property path | Best for |
|---|---|---|---|
| Class-level constraint | Yes, if the validator targets an interface | Yes, through the context | Rules used in several places, or errors tied to a specific field |
| `@AssertTrue` method | No | No, the path is the method's property name | A one-off rule in a single DTO |
| Check in the service layer | Yes | Not applicable | Rules that need a database or other beans |
To reuse one validator, make the validator's type parameter an interface that your DTOs implement, for example ConstraintValidator<PasswordsMatch, PasswordHolder>. Hibernate Validator also ships @ScriptAssert for inline expressions. It is specific to that provider, it has been deprecated since Hibernate Validator 6.2, and it evaluates scripts at runtime. Prefer the approaches in the table.
Testing the rule without Spring
A class-level constraint is a pure Java rule, so a plain Validator test is enough. It runs in milliseconds and needs no web layer.
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.util.Set;
import org.junit.jupiter.api.Test;
class PasswordsMatchTest {
private final Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
@Test
void reportsMismatchOnConfirmPassword() {
RegisterRequest request =
new RegisterRequest("[email protected]", "secret123", "different");
Set<ConstraintViolation<RegisterRequest>> violations = validator.validate(request);
assertThat(violations).hasSize(1);
ConstraintViolation<RegisterRequest> violation = violations.iterator().next();
assertThat(violation.getPropertyPath().toString()).isEqualTo("confirmPassword");
assertThat(violation.getMessage()).isEqualTo("passwords do not match");
}
@Test
void acceptsMatchingPasswords() {
RegisterRequest request =
new RegisterRequest("[email protected]", "secret123", "secret123");
assertThat(validator.validate(request)).isEmpty();
}
@Test
void missingPasswordIsLeftToFieldConstraints() {
RegisterRequest request = new RegisterRequest("[email protected]", null, "secret123");
Set<ConstraintViolation<RegisterRequest>> violations = validator.validate(request);
assertThat(violations)
.extracting(v -> v.getPropertyPath().toString())
.containsExactly("password");
}
}The third test checks the null-handling rule. Only the @NotBlank violation on password appears, and the class-level validator stays silent.
Common mistakes
- Putting the annotation on a component.
@PasswordsMatchis written forElementType.TYPE. On a record component, the compiler rejects it. - Dereferencing fields without a null check. The class-level validator runs even when field constraints fail, so any field may be
null. - Forgetting
addConstraintViolation(). AfterdisableDefaultConstraintViolation(), the build call does nothing until you add the violation. - Losing global errors in the handler. Reading only
getFieldErrors()hides violations that have no property node. - Expecting ordering between rules. Without groups or a
@GroupSequence, no order is guaranteed between field and class-level constraints. If a rule must run only after the fields are valid, put it in a later group in a group sequence.
Exercise
A DTO has fields discountCode and discountPercent. The rule is that either both are present or both are absent. You write a class-level constraint whose validator reports a violation with context.disableDefaultConstraintViolation() and buildConstraintViolationWithTemplate(...).addPropertyNode("discountCode").addConstraintViolation(). Which exception handler loop shows this error to the client: one over getFieldErrors() or one over getGlobalErrors()? What would change if you removed the addPropertyNode call and kept the default violation?
Show answer
The loop over getFieldErrors() shows it, because the violation has a property path (discountCode), so Spring records it as a FieldError. If you removed addPropertyNode and kept the default violation, the path would be empty and Spring would record an ObjectError. Then only a loop over getGlobalErrors() would show it, and the handler from the earlier chapter would return a 400 with an empty errors map.
Exercise
Why should a class-level validator return true when a field it reads is null?
Show answer
Bean Validation runs all constraints in one pass, so the class-level validator can see a null that @NotNull or @NotBlank is already reporting. Returning true avoids a NullPointerException and keeps the "is it present" rule in a single place, so the client does not get two errors for the same missing value.