Spring Boot supports custom validators for rules that go beyond standard Bean Validation constraints, implemented either through a custom ConstraintValidator paired with a new annotation or by implementing Spring's Validator interface directly.
Key Points: • Create a custom annotation, such as @ValidPassword, and back it with a class implementing ConstraintValidator<ValidPassword, String>. • The isValid() method contains the actual validation logic and can access other fields for cross-field checks. • Apply the custom annotation on a field just like a built-in constraint, and it participates in @Valid validation automatically. • Alternatively, implement Spring's org.springframework.validation.Validator interface for validators explicitly invoked in a controller. • Custom validators are ideal for domain rules that built-in annotations can't express, like verifying a password meets multiple composite conditions.
Example: A @ValidPassword annotation backed by a ConstraintValidator checks that a password field has at least one digit, one uppercase letter, and a minimum length, all enforced automatically the moment @Valid runs on the request DTO.
Code Example:
public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
return password != null
&& password.length() >= 8
&& password.matches(".*[A-Z].*")
&& password.matches(".*[0-9].*");
}
}Interview Tip: A concise interview answer is:
"For custom rules, I create a custom annotation backed by a ConstraintValidator implementation, so it plugs into the existing @Valid pipeline just like a built-in constraint such as @NotNull. That keeps custom domain validation, like password complexity rules, declarative and consistent with the rest of the validation setup."