java - Dropwizard 自定义验证注释不起作用

标签 java validation jersey dropwizard

我尝试使用自定义验证注释一次应用多个常见注释,如下所示:

@Retention(RetentionPolicy.RUNTIME)
@Length(max=25, min=1, message="invalid length")
@NotNull
@Pattern(regexp = "[a-zA-Z0-9]{1, 25})")
public @interface MyAnnotation {
}

并在我的模型类中使用它,如下所示:

@MyAnnotation
public String firstName;

这些验证都不起作用,但在模型类本身中使用时它们会按预期工作。我还尝试在应用程序运行方法中注册 MyAnnotation,但这也不起作用。

environment.jersey().register(MyAnnotation.class);

为了使用自定义验证,我还需要做什么?

最佳答案

直接注释字符串:

@Pattern(regexp = "[a-zA-Z0-9]{1, 25})")
@NotNull
@Length(max=25, min=1, message="invalid length")
public String firstName; 

或者创建一个 validator ,例如:

class MyAnnotatationValidator implements ConstraintValidator<MyAnnotation, String>{
  @Override
  public void initialize(MyAnnotation a){}
  @Override
  public boolean isValid(String s, ConstraintValidationContext c) {
    return s != null && (s.length() > 0 && s.length() < 26) && s.matches("[a-zA-Z0-9]{1, 25})";  
  }
}

并且有

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyAnnotatationValidator.class)
public @interface MyAnnotation {
  String message() default = "{MyAnnotation}";
  Class<?>[] groups() default {};
  Class<? extends Payload> payload() deafult {};
}

关于java - Dropwizard 自定义验证注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38153880/

相关文章:

java - REST Web 服务及其过滤器

java - @Inject 在 Struts 2 中的 Jersey REST web 服务中不起作用

c# - 如何创建用于检查特定时间范围的正则表达式

windows - 批处理文件: parsing command line inputs

java - 如何使用页面工厂在testng中运行多个测试类?

java - maven-dependency-plugin <includes> 标签不起作用

php - 将表单 POST 提交到另一个页面,但在重定向之前进行验证,如果验证失败,则保留在同一页面上

java - Google Guice 和 JPA 注入(inject) - 奇怪的错误

java - Spring Batch CompositeItemWriter事务回滚问题

java - JodaTime:获取与 utc 相比具有偏移 xyz 的 DateTimeZone