Reputation: 2967
I want to create my own Annatotation Constraint, because I hava a String which contains a list of emails seperated by a comma.
I follow the doc from here : http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html
In my project I use Hibernate Validator as Provider for Bean validation. And I notice that Hibernate provide an @Email
constraint.
Is it possible to call the org.hibernate.validator.constraints.impl.EmailValidator::isValid from my own Validator class ?
I made the following and its work:
public class EmailsValidator implements ConstraintValidator<Emails, String> {
private EmailValidator emailValidator = new EmailValidator();
@Override
public void initialize(Emails constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("EmailsValidator::isValid");
if (value == null || value.isEmpty()) {
return true;
}
final String[] emails = value.split(",\\s*");
for (String anEmail : emails) {
System.out.println("anEmail = " + anEmail);
if (!emailValidator.isValid(anEmail, context)) {
return false;
}
}
return true;
}
}
Is it the most efficient way to make it ?
Bye.
Upvotes: 1
Views: 742
Reputation: 18990
I think this approach generally works, but you should be aware that you're relying on an internal class of Hibernate Validator, which might be changed in future releases. An indeed it will be moved to another package in HV 4.3. Alternatively you might just copy the regular expressions into your own validator.
Upvotes: 1