Is there a uuid validator annotation?

和自甴很熟 提交于 2021-02-06 08:30:45

问题


I can't find a @UUID (or similar) annotation for validating input parameters in a java web app.

I've looked so far in

  1. javax.validation.constraints
  2. org.hibernate.validator.constraints

回答1:


yes, build it by yourself

@Target(ElementType.FIELD)
@Constraint(validatedBy={})
@Retention(RUNTIME)
@Pattern(regexp="^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
public @interface UUID {
    String message() default "{invalid.uuid}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}



回答2:


The solution from Jaiwo99 works, but I was unable to set a custom message from the outside (it is overriden by the message from @Pattern). If you need that, I propose that you simply use something like this:

@Pattern(regexp = SomeUtilClass.UUID_PATTERN, message = "TokenFormatError")
private String token;

You can put the pattern in some static final field to avoid duplication:

public static SomeUtilClass {
    public static final String UUID_PATTERN = "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$";
}


来源:https://stackoverflow.com/questions/37320870/is-there-a-uuid-validator-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!