Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 hisPR 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 modeExit fullscreen mode

In order to make it work, just create this class in your project and call the methodUUIDValidator.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 checkthis link.

...The end!

That's all! Thank you for this reading 😁

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
pdfreviewer profile image
pdfreviewer
  • Joined

I would prefer

publicbooleanisValidUUID(finalStringinput){try{UUID.fromString(input);returntrue;}catch(Exceptione){returnfalse;}}
Enter fullscreen modeExit fullscreen mode


`

CollapseExpand
 
miltonsermoud profile image
Milton Sermoud
  • Joined
• Edited on• 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.

CollapseExpand
 
pdfreviewer profile image
pdfreviewer
  • Joined

"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.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp