In my project, I use UUID.fromString()
to convert string to UUID
, but if the string is not UUID
type, it will throw exception
, so how can I validate this string?
Asked
Active
Viewed 1.4e+01k times
69

Elton Wang
- 1,145
- 1
- 8
- 18
-
2Try http://stackoverflow.com/questions/18724750/foolproof-way-of-differentiating-string-and-uuid - it might be just what you are looking for. – Ewald Nov 18 '13 at 05:58
-
2Possible duplcate of: http://stackoverflow.com/questions/7905929/how-to-test-valid-uuid-guid – Masudul Nov 18 '13 at 05:59
-
I added a UUID validator to Apache Commons Validator. It's not yet been merged, but you can vote for it here: https://github.com/apache/commons-validator/pull/68 – Daniel Heid Jan 07 '22 at 09:18
2 Answers
118
Handle the exception and do something in that case. For example :
try{
UUID uuid = UUID.fromString(someUUID);
//do something
} catch (IllegalArgumentException exception){
//handle the case where string is not valid UUID
}

Saša Šijak
- 8,717
- 5
- 47
- 82
-
23It might be unexceptional to have data that contain UUIDs and other elements. Exceptions should be exceptional, not routine; don't use exceptions for flow control. There are [a number of reasons for this.](https://www.google.com/search?q=exception+flow+control) – erickson Nov 18 '13 at 15:36
-
1http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html#fromString(java.lang.String) that method throws that exception. It is perfectly reasonable to handle it there. And this handling in this particular case would probably be just some logging for further reference. – Saša Šijak Nov 18 '13 at 16:09
-
10It's reasonable to handle it there if, in the context of your application, you expect to have a UUID and it would be exceptional for the string to be an invalid format. On the other hand, if your application is a parser, and the grammar accepted UUIDs and identifiers of other types at a particular alternative, testing the format like this would be inappropriate. – erickson Nov 18 '13 at 17:15
-
74This would not work! I run into an issue where the someUUID is "1-1-1-1-1" but UUID.formString("1-1-1-1-1") returned "00000001-0001-0001-0001-000000000001", basically it does convert into an UUID representation. you need to use regex like `Pattern p = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$");` and then `p.matcher(uuidString).matches();` – mkilic Mar 23 '16 at 15:06
-
The test for this exception is just for trivial cases and it should not be used for validation. Not just because it is an exception, as mentioned, but also because the JVM might use simpler tests than you might expect. My for instance uses this test to throw the exception: `String[] var1 = var0.split("-"); if (var1.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + var0); }` This also explains the above comment. – Victor Mar 09 '18 at 19:05
-
35Please note that this does not work for Java 8. See here https://bugs.java.com/view_bug.do?bug_id=8159339 . As an alternative you can use "UUID.fromString(uuid).toString().equals(uuid)" – ampofila Aug 08 '18 at 11:57
-
6@mkilic Sounds like a bug in the JDK. Also sucks we don't have `UUID.tryParse(String value)` or similar. – Josh M. Jan 04 '19 at 14:11
-
-
2The java.util.UUID.fromString() is doing that validation. Its a shame language designers did not expose a boolean isValid() method - seems most commonsensical thing to do and could have reused the isValid in fromString() – sparker Jun 25 '21 at 15:39
82
You should use regex to verify it e.g.:
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$
test it with e.g.g 01234567-9ABC-DEF0-1234-56789ABCDEF0
or with brackets
^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?$

Wiktor Stribiżew
- 607,720
- 39
- 448
- 563

Imran
- 5,376
- 2
- 26
- 45
-
9Just throwing my 2 cents here, as I saw the other answer with 35 up-votes. People should use this one if those are the 2 choices. Mainly because I found that the JDK I was using was simply throwing the exception based on this trivia if -> `String[] var1 = var0.split("-"); if (var1.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + var0); }` – Victor Mar 09 '18 at 19:02
-
https://stackoverflow.com/questions/18724750/foolproof-way-of-differentiating-string-and-uuid – Victor Mar 09 '18 at 22:15
-
The second regular expression above that allows brackets has a problem. It considers a UUID with only an opening or closing curly brace valid, ex: {77921671-41fa-4f61-83ea-5d60b76a264e – MartinPicker Oct 04 '18 at 12:44
-
3This is far more prone to breakage, and far more verbose and unnecessary than a simple try/catch to parse the UUID as in another answer here. – Josh M. Jan 04 '19 at 14:10
-
You could condense the redundancy of the {4} length groups by wrapping it in a non-capturing group with a {3} quantifier. E.g. (^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$) – TomPlum Nov 15 '19 at 09:37
-
If you need to verify the string in a performance critical section then regex test is the better option. Other than that I agree with @JoshM. Try/catch block is much more readable and understandable. – tbaskan Jun 19 '20 at 08:55
-
Actually, one more validation is needed. The first char of the 3rd segment defines the version of the UUID, and it cannot be higher than 5. (I've just faced this problem, this UUID was rejected by a very strict validator: 7396683c-0759-6411-b974-a0d3c123d81e) – Selindek Aug 28 '20 at 12:44
-
@MartinPicker if you're using PCREs, this could be fixed using a possessive lookbehind `\{?\p{XDigit}{8}-(?:\p{XDigit}{4}-){3}\p{XDigit}{12}(?:(?<=\{.{36})+\})?` – rampion Jun 30 '21 at 20:35
-
Most suggestions are to use regex.. Thanks https://www.code4copy.com/java/validate-uuid-string-java/ – Srinath Thota Jul 02 '21 at 08:01