DEV Community

Cover image for Checking if String UUID is valid with Java

Checking if String UUID is valid with Java

Milton Sermoud on June 30, 2022

First words All credits to Daniel Heid. This code is based on his PR in the hibernate-validator repository on Github. Thank you, Daniel!...
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.