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
I can't find a @UUID
(or similar) annotation for validating input parameters in a java web app.
I've looked so far in
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 {};
}
[Updated]
The solution from @Jaiwo99 will not display the specified message, it will instead display the error message from @Pattern
. To fix this issue, just add @ReportAsSingleViolation
annotation to @Jaiwo's solution. (@LudovicRonsin pointed this out in a comment to this answer, and @helospark in a comment to @Jaiwo99's answer.)
@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}$")
@ReportAsSingleViolation
public @interface UUID {
String message() default "{invalid.uuid}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
[Old Answer]
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}$";
}
At the time of the question there wasn't one but in the meantime it has been added starting with org.hibernate.validator:hibernate-validator:8.0.0.Final
https://docs.jboss.org/hibernate/stable/validator/api/org/hibernate/validator/constraints/UUID.html
Same as @Jaiwo99's answer , but as @mrzli pointed out, the pattern's message overrides any custom messages. Using message in the @Pattern will fix that if you want custom messages.
@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}$", message = "Not a valid UUID")
public @interface UUID {
String message() default "{invalid.uuid}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}