1

我想创建自己的 Annatotation 约束,因为我有一个字符串,其中包含用逗号分隔的电子邮件列表。

我从这里关注文档:http: //docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html

在我的项目中,我使用 Hibernate Validator 作为 Bean 验证的提供者。我注意到 Hibernate 提供了一个@Email约束。

是否可以从我自己的 Validator 类中调用 org.hibernate.validator.constraints.impl.EmailValidator::isValid ?

我做了以下及其工作:

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;
}

}

这是最有效的方法吗?

再见。

4

1 回答 1

1

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.

于 2012-04-12T20:32:44.643 回答