0

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?

MarkHuntDev
  • 181
  • 3
  • 21

1 Answers1

2

There is no official way to reuse a validator in another one.

What you can do though would be to initialize an EmailValidator attribute in initialize() and call its isValid() method in your isValid() method.

Keep in mind that EmailValidator is internal so it might be subject to changes in the future.

Guillaume Smet
  • 9,921
  • 22
  • 29