问题
I can't find a @UUID
(or similar) annotation for validating input parameters in a java web app.
I've looked so far in
- javax.validation.constraints
- 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