Created
November 27, 2018 15:18
-
-
Save mindhaq/ffc3378a271cb7e91b3819ff1abb675c to your computer and use it in GitHub Desktop.
Java validator for UUIDs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.validation.Constraint; | |
import javax.validation.Payload; | |
import javax.validation.constraints.Pattern; | |
import java.lang.annotation.Documented; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.Target; | |
import static java.lang.annotation.ElementType.ANNOTATION_TYPE; | |
import static java.lang.annotation.ElementType.FIELD; | |
import static java.lang.annotation.ElementType.METHOD; | |
import static java.lang.annotation.ElementType.PARAMETER; | |
import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
/** | |
* Validation constraint for a UUID in string format. | |
* | |
* e.g. 6cfb0496-fa35-4668-a970-78a873d7970e | |
* | |
* @author Rüdiger Schulz <[email protected]> | |
*/ | |
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") | |
@Retention(RUNTIME) | |
@Target({METHOD, FIELD, PARAMETER, ANNOTATION_TYPE}) | |
@Constraint(validatedBy = {}) | |
@Documented | |
public @interface UUID { | |
String message() default "UUID has wrong format"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
} |
Right; this is meant for validating e.g. incoming path variables or request parameters in a spring MVC controller method.
@GetMapping("/change/{code}")
public String confirmChange(@PathVariable @UUID String code) {
// ...
}
I just created a bean validation annotation and requested a merge to Hibernate Validators. If you want to support this, just vote for it here:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You cannot apply the '@pattern' annotation to something (java.util.UUID) that is not a CharSequence