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?
So to check if a string is valid UUID we can use this regular expression, // Regular expression to check if string is a valid UUID const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi; This matches all the valid UUID since it checks for the above test cases.
Use the . match() method to check whether String is UUID.
UUIDs support input of case-insensitive string literal formats, as specified by RFC 4122. In general, a UUID is written as a sequence of hexadecimal digits, in several groups optionally separated by hyphens, for a total of 32 digits representing 128 bits.
Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8 , 9 , A , or B . Before performing the regex, I might add a quick simple IF() to test if the length of the string is 32 or 36 characters long. If not, it's not a UUID hex string.
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 }
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}\}?$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With