Problem
How can I tell if a variable includes a valid UUID/GUID?
I’m currently only interested in validating kinds 1 and 4, but this should not limit your responses.
Asked by Marek Sebera
Solution #1
Currently, UUID’s are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here. The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of the third block).
As a result, validating a UUID…
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i
…ensures you have an RFC4122-compliant canonically formatted UUID that is Version 1 through 5 and the proper Variant.
Braces and are not canonical terms. They are a byproduct of certain systems and applications.
It’s simple to adapt the above regex to fit the original question’s requirements.
HINT: regex group/captures
To avoid matching NIL UUID:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
Answered by Gambol
Solution #2
regex saves the day
/^[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('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}\}?$/
Answered by ryanb
Solution #3
Here are the corresponding regexes for checking or validating a certain UUID version.
The first character of the third group represents the version number: [VERSION NUMBER][0-9A-F]3: [VERSION NUMBER][0-9A-F]3:
Answered by Ivan Gabriele
Solution #4
Validator is a package that is recommended if you are using Node.js for development. It comes with all of the regexes needed to validate various versions of UUIDs, as well as a variety of other validation methods.
The npm link is here: Validator
var a = 'd3aa88e2-c754-41e0-8ba6-4198a34aa0a2'
v.isUUID(a)
true
v.isUUID('abc')
false
v.isNull(a)
false
Answered by Neeraj Sharma
Solution #5
with some changes thanks to @usertatha
function isUUID ( uuid ) {
let s = "" + uuid;
s = s.match('^[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 (s === null) {
return false;
}
return true;
}
Answered by Souhaieb
Post is based on https://stackoverflow.com/questions/7905929/how-to-test-valid-uuid-guid