【问题标题】:Creating custom validation annotation using built-in annotations使用内置注解创建自定义验证注解
【发布时间】:2014-07-07 02:26:46
【问题描述】:

在我正在工作的系统中,username 必须是 emailcell number

我正在使用Hibernate Validator 来验证 bean。

我想创建一个自定义注解@Username,以便验证一个bean 属性是email 还是cell number

可以使用@Email 验证电子邮件,使用@Pattern 使用正则表达式验证单元格编号,但我不知道如何编写自定义验证器,以便可以重复使用上述内置注释。

我参考了Creating custom validator 部分来创建自定义验证器。

基本上我的问题是,

如何使用内置验证注解(@Email@Pattern)组成一个新注解 @Username,以便 @Username 验证属性是 email 还是 cell number

// @Email or @Pattern("...") ???
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface Username {
   /* ... */
}

【问题讨论】:

    标签: java validation hibernate-validator


    【解决方案1】:

    如果您想符合 Bean 验证,则不能。没有约束的 OR 组合的概念。但是,如果您使用的是 Hibernate Validator,并且您可以使用特定于提供程序的功能,则可以在 Hibernate Validator 中使用布尔组合 - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-boolean-constraint-composition

    @Target(FIELD)
    @Retention(RUNTIME)
    @Constraint(validatedBy = {})
    @Documented
    @ConstraintComposition(OR)
    @Email
    @Pattern("...")
    public @interface Username {
       /* ... */
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2018-10-25
      • 1970-01-01
      • 2014-09-24
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      相关资源
      最近更新 更多