java 是否有 uuid 验证器注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37320870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a uuid validator annotation?
提问by Emanuel George Hategan
I can't find a @UUID
(or similar) annotation for validating input parameters in a java web app.
我@UUID
在 Java Web 应用程序中找不到用于验证输入参数的(或类似的)注释。
I've looked so far in
我看过这么远
- javax.validation.constraints
- org.hibernate.validator.constraints
- javax.validation.constraints
- org.hibernate.validator.constraints
回答by Jaiwo99
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 {};
}
回答by mrzli
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:
Jaiwo99 的解决方案有效,但我无法从外部设置自定义消息(它被来自 的消息覆盖@Pattern
)。如果你需要,我建议你简单地使用这样的东西:
@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}$";
}