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.

try{
    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 =
            Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");

    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

@Testable
public class UtilTests {
    @Test
    public void is_valid_uuid_ok(){
        assertTrue(Utils.isValidUUID("009692ee-f930-4a74-bbd0-63b8baa5a927"));
    }
    @Test
    public void is_valid_uuid_false(){
        assertTrue(!Utils.isValidUUID(null));
        assertTrue(!Utils.isValidUUID(""));
        assertTrue(!Utils.isValidUUID("test-ss-ss-ss-s"));
        assertTrue(!Utils.isValidUUID("009692ee-f9309-4a74-bbd0-63b8baa5a927"));
        assertTrue(!Utils.isValidUUID("1-1-1-1"));
    }
}

One response to “How to validate UUID String in Java”

Leave a Reply to Daniel Heid Cancel 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.