Skip to content

Instantly share code, notes, and snippets.

@mindhaq
Created November 27, 2018 15:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mindhaq/ffc3378a271cb7e91b3819ff1abb675c to your computer and use it in GitHub Desktop.
Save mindhaq/ffc3378a271cb7e91b3819ff1abb675c to your computer and use it in GitHub Desktop.
Java validator for UUIDs
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 <rs@mindhaq.com>
*/
@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 {};
}
@mojtabaafshaar
Copy link

You cannot apply the '@pattern' annotation to something (java.util.UUID) that is not a CharSequence

@mindhaq
Copy link
Author

mindhaq commented Jan 27, 2021

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) { 
    // ...
}

@dheid
Copy link

dheid commented Jan 9, 2022

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