DEV Community

Cover image for Checking if String UUID is valid with Java
Milton Sermoud
Milton Sermoud

Posted on

Checking if String UUID is valid with Java

First words

All credits to Daniel Heid. This code is based on his PR in the hibernate-validator repository on Github. Thank you, Daniel!

The code

If you don't want to read me, just copy the code below and follow the instructions I leave up in the first lines of the code.

/* 
 * This code is based on this PR: https://github.com/hibernate/hibernate-validator/pull/1199
 * All credits to Daniel Heid (dheid). I just made some adjustments.
 * In order to apply this on your situation, just create this class and call the method "isValidStringUUID". As its param, pass in your string UUID.
*/

public class UUIDValidator {
    enum LetterCase {

        /**
         * Only lower case is valid
         */
        LOWER_CASE,

        /**
         * Only upper case is valid
         */
        UPPER_CASE,

        /**
         * Every letter case is valid
         */
        INSENSITIVE

    }

    private static LetterCase letterCase = LetterCase.LOWER_CASE;

    private static final int[] GROUP_LENGTHS = { 8, 4, 4, 4, 12 };

    public static boolean isValidStringUUID(String value) {
        if ( value == null ) {
            return false;
        }
        int valueLength = value.length();
        if ( valueLength == 0 ) {
            return false;
        }
        else if ( valueLength != 36 ) {
            return false;
        }

        int groupIndex = 0;
        int groupLength = 0;
        int checksum = 0;
        for ( int charIndex = 0; charIndex < valueLength; charIndex++ ) {

            char ch = value.charAt( charIndex );

            if ( ch == '-' ) {
                groupIndex++;
                groupLength = 0;
            }
            else {

                groupLength++;
                if ( groupLength > GROUP_LENGTHS[groupIndex] ) {
                    return false;
                }

                int numericValue = Character.digit( ch, 16 );
                if ( numericValue == -1 ) {
                    // not a hex digit
                    return false;
                }
                if ( numericValue > 9 && !hasCorrectLetterCase( ch ) ) {
                    return false;
                }
                checksum += numericValue;
            }
        }
        // NIL UUID
        if ( checksum == 0 ) {
            return false;
        }
        return true;
    }
    private static boolean hasCorrectLetterCase(char ch) {
        if ( letterCase == null ) {
            return true;
        }
        if ( letterCase == LetterCase.LOWER_CASE && !Character.isLowerCase( ch ) ) {
            return false;
        }
        return letterCase != LetterCase.UPPER_CASE || Character.isUpperCase( ch );
    }
}
Enter fullscreen mode Exit fullscreen mode

In order to make it work, just create this class in your project and call the method UUIDValidator.isValidStringUUID(String your_UUID_String_Goes_Here).

In this code we have all kind of validations: for if it's null, if it's a blank string, if its length is incorrect, if the digits of the UUID String contains only hex digits, if each group of the UUID contains the right amount of characters, etc, etc.

If you want a more specialized validator, don't forget to check the PR I mentioned before. It also contains how to get the UUID version and its variation.

Good to read

If you want to dive in on this subject (it's definitely so rich and interesting), you can check this link.

...The end!

That's all! Thank you for this reading 😁

Top comments (3)

Collapse
 
pdfreviewer profile image
pdfreviewer

I would prefer

public boolean isValidUUID(final String input) {
    try {
        UUID.fromString(input);
        return true;
    } catch (Exception e) {
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode


`

Collapse
 
miltonsermoud profile image
Milton Sermoud • Edited

There are some cases that this doesn't work. Try to pass in the string "f-e-4-a-a". The result will be true and it's against the UUID patterns.

Collapse
 
pdfreviewer profile image
pdfreviewer

"f-e-4-a-a" will be parsed as "0000000f-000e-0004-000a-00000000000a" and I agree that it's against the general UUID patterns. I think it would be helpful if such cases are mentioned at the beginning of the article.