For example, I have got a class:
@Getter
@Setter
class Notification {
private String recipient;
private Channel channel;
enum Channel {
SMS, EMAIL
}
}
I could define my own Validator, for instance:
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = {RecipientValidator.class})
@interface ValidRecipient {
// required arguments of validation annotation
}
class RecipientValidator implements ConstraintValidator<ValidRecipient, Notification> {
@Override
public void initialize(ValidRecipient annotation) {
}
@Override
public boolean isValid(Notification value, ConstraintValidatorContext context) {
boolean result = true;
if (value.getChannel() == SMS) {
return matches(value.getRecipient(), "<phone-number-regexp>");
}
if (value.getChannel() == EMAIL) {
// can I reuse Hibernate's Email Validation there?
return matches(value.getRecipient(), "<email-regexp>");
}
return result;
}
}
Of course I can google regexp of email and copy-paste there but Hibernate's Bean Validation implementation already has the Email Validation (under @Email annotation). Is there a way to reuse that validation implementation in my custom validator?