How to test valid UUID/GUID?

How to test valid UUID/GUID?

How to check if variable contains valid UUID/GUID identifier ?
I’m currently interested only in validating types 1 and 4, but it’s not limit for your answer.


Solution 1:

Currently, UUID’s are as specified in RFC4122.

Therefore to validate a UUID…


…ensures you have a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.

NOTE: Braces { and } are not canonical. They are an artifact of some systems and usages.

Easy to modify the above regex to meet the requirements of the original question.

HINT: regex group/captures

Solution 2:

regex to the rescue


or with brackets


Solution 3:

If you are using Node.js for development, it is recommended to use a package called Validator. It includes all the regexes required to validate different versions of UUID’s plus you get various other functions for validation.

Here is the npm link: Validator

var a = 'd3aa88e2-c754-41e0-8ba6-4198a34aa0a2'

Solution 4:

If you want to check or validate a specific UUID version, here are the corresponding regexes.

Note that the only difference is the version number, which is explained in 4.1.3. Version chapter of UUID 4122 RFC.

The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3} :

  • UUID v1 :

  • UUID v2 :

  • UUID v3 :

  • UUID v4 :

  • UUID v5 :


Solution 5:

Beside Gambol’s answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It’s used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:


[1] The question is about checking variables, so we should include the user-unfriendly form as well.

Related:  Can we omit parentheses when creating an object using the “new” operator?

Solution 6:

All type-specific regexes posted so far are failing on the “type 0” Nil UUID, defined in 4.1.7 of the RFC as:

The nil UUID is special form of UUID that is specified to have all 128 bits set to zero: 00000000-0000-0000-0000-000000000000

To modify Wolf’s answer:


Or, to properly exclude a “type 0” without all zeros, we have the following (thanks to Luke):