How to validate UUID String in Java

Many times we are supposed to get a string and that should be a valid UUID or GUID. Unfortunately Java UUID class don’t provide any function to validate whether a string is valid UUID or not.

In many places, you will see to use the UUID java class function fromString, if any exception then the string is not valid UUID. That function is given below, But this will fail in some cases, and using exceptions for doing some functionality is not the correct way.

    UUID uuid = UUID.fromString(someUUID);
    //do something
} catch (IllegalArgumentException exception){
    //handle the case where string is not valid UUID 

For example this function will parse “1-1-1-1-1” and return “00000001-0001-0001-0001-000000000001”. So this is not the correct way to do this.

UUID check can be easily done using regular expression as given below.

    private final static Pattern UUID_REGEX_PATTERN =

    public static boolean isValidUUID(String str) {
        if (str == null) {
            return false;
        return UUID_REGEX_PATTERN.matcher(str).matches();

Here are some sample tests for the above function

public class UtilTests {
    public void is_valid_uuid_ok(){
    public void is_valid_uuid_false(){

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.