0 day streak
java / expert
Snippet

Custom Constraint Validators for Complex Domain Logic

Beyond simple field validation, Spring supports class-level constraints via ConstraintValidator. This allows for complex validation logic involving multiple fields within an object, maintaining domain integrity.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, UserDto> {
@Override
public boolean isValid(UserDto user, ConstraintValidatorContext context) {
return user.getPassword().equals(user.getMatchingPassword());
}
}
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
public @interface PasswordMatches {
String message() default "Passwords don't match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
spring
Breakdown
1
implements ConstraintValidator<PasswordMatches, UserDto>
Links the custom annotation to the logic that validates the specific DTO.
2
@Constraint(validatedBy = PasswordMatchesValidator.class)
The annotation metadata that points Spring to the implementation class for validation logic.
3
user.getPassword().equals(user.getMatchingPassword())
The actual business logic comparing two fields within the DTO.