A UUID regex is useful at input boundaries, but it should be honest about what it checks. A pattern can confirm the shape, version and variant; it cannot prove that an ID exists in your system or grants access.
Key takeaways
- Use strict anchors so partial matches do not pass.
- Check version and variant when those details matter.
- Prefer a UUID parser in application code when one is available.
Strict UUID regex
This pattern validates the common hyphenated UUID shape and checks the variant nibble. It accepts versions 1 through 8, which covers modern UUID layouts while rejecting many strings that only look close.
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iUUID v4 only regex
Use a version-specific pattern when your API only accepts one UUID version. For UUID v4, the first character of the third group must be 4.
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iHandling braces, URNs and compact UUIDs
Users paste identifiers from many places. Some tools wrap GUIDs in braces, some include a urn:uuid: prefix, and some remove hyphens. Decide which formats you will accept, then normalize to one storage format.
// Compact 32-character UUID string
/^[0-9a-f]{32}$/i
// URN format
/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i