Custom Constraint Annotations
Create a custom @UniqueEmail annotation with a ConstraintValidator implementation.
When Standard Constraints Are Not Enough
Standard Bean Validation annotations cover common cases. For domain-specific rules (e.g., unique email, valid IBAN, password strength), create custom constraint annotations.
Defining the Constraint Annotation
Create an annotation with @Constraint(validatedBy = ...), required message, groups, and payload elements, and the appropriate retention/target.
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
@Documented
@Constraint(validatedBy = UniqueEmailValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface UniqueEmail {
String message() default "Email already registered";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}