How to Validate a UUID in JavaScript and Python
By SimpleTools24Published 3 min read
To validate a UUID in JavaScript, test it against a strict regular expression or use validate() from the uuid package. In Python, try to construct uuid.UUID(value) and catch ValueError, then optionally check that str() of the result equals the input if you require the canonical format. Decide up front whether you accept uppercase, braces or values without hyphens, because built-in parsers are often more lenient than you expect.
In this guide
Decide What "Valid" Means
Before writing code, pick a policy:
| Policy | Accepts | Good for |
|---|---|---|
| Canonical only | Lowercase, hyphenated 8-4-4-4-12 | APIs with strict contracts |
| Standard, any case | Upper or lower case, hyphenated | Most web forms and APIs |
| Lenient | Braces, no hyphens, urn:uuid: prefix | Import tools, admin consoles |
| Version-specific | Only v4, or only v7 | Rarely needed; can break future changes |
Whatever you accept, store and return one canonical form (lowercase with hyphens) to avoid duplicates that differ only in formatting.
JavaScript
With a Regex
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isUuid(value) {
return typeof value === 'string' && UUID_RE.test(value.trim());
}This checks the format plus a standard version (1–8) and variant. Remove .trim() if surrounding whitespace should be an error. More patterns, including v4-only and loose checks, are in UUID regex patterns.
With the uuid Package
import { validate, version } from 'uuid';
validate('9b2c1f7e-5d3a-4c8b-a1e2-7f6d0c9b3a54'); // true
version('9b2c1f7e-5d3a-4c8b-a1e2-7f6d0c9b3a54'); // 4The package's validate also accepts the nil and max UUIDs. Check its documentation for the exact rules in the version you install.
Normalising
const canonical = (s) => s.trim().toLowerCase().replace(/^\{|\}$/g, '');Python
Parse and Catch
import uuid
def is_uuid(value: str) -> bool:
try:
uuid.UUID(value)
return True
except (ValueError, TypeError, AttributeError):
return Falseuuid.UUID() is lenient: it accepts uppercase, braces, the urn:uuid: prefix and the 32-digit compact form. That's convenient for imports but may be looser than your API contract.
Strict Canonical Check
def is_canonical_uuid(value: str) -> bool:
try:
return str(uuid.UUID(value)) == value
except (ValueError, TypeError, AttributeError):
return FalseBecause str() produces lowercase hyphenated output, this only accepts the canonical form.
Checking the Version
u = uuid.UUID(value)
if u.version != 4:
raise ValueError('expected a version 4 UUID')Note that u.version is only meaningful for the standard RFC variant; check u.variant == uuid.RFC_4122 first if you need to be thorough.
Java and C# Notes
- Java:
UUID.fromString()has historically been lenient about the length of each group in some versions; validate with a regex first if you need strictness. - C#:
Guid.TryParse()accepts several formats, including braces and the compact form. UseGuid.TryParseExact(value, "D", out var g)to require the standard hyphenated form.
Where to Validate
- At the edge: validate path parameters and request bodies, returning a clear 400 error rather than letting the database throw.
- In the database: use a native
uuidoruniqueidentifiercolumn, which rejects malformed values. - Not as authorisation: a valid UUID says nothing about whether the record exists or the user may access it.
When validation fails unexpectedly, why a UUID is invalid lists the usual culprits, such as hidden whitespace and smart quotes.
Checking Real Data First
Before choosing a policy, look at the IDs your systems actually produce. The UUID validator checks up to 1,000 values at once, accepts standard, compact, braced and URN forms, and shows each value's version, variant and canonical form. For a single ID, the UUID decoder also reveals timestamps in time-based versions.
Validating in API Schemas
If your API uses a schema library, let it do the work:
- JSON Schema:
{ "type": "string", "format": "uuid" }. Many validators support theuuidformat, though some only check it when format validation is enabled. - Zod (TypeScript):
z.string().uuid()validates the standard format. - Pydantic (Python): annotate a field as
uuid.UUIDto parse and validate it automatically. - OpenAPI:
type: string, format: uuiddocuments the expectation for clients and code generators.
Schema validation keeps the rule in one place and produces consistent error messages.
Writing Good Error Messages
When validation fails, tell the caller what's wrong without echoing sensitive data:
- "orderId must be a UUID, for example 9b2c1f7e-5d3a-4c8b-a1e2-7f6d0c9b3a54"
- Include the field name and the expected format.
- Avoid stack traces or database errors, which leak implementation details.
Frequently Asked Questions
How do I check if a string is a UUID in JavaScript?
Use a strict regex like the one above, or validate() from the uuid package.
Does Python's uuid.UUID() validate input?
It raises ValueError for malformed input, but it accepts several formats. Compare with str() for a strict check.
Should I reject uppercase UUIDs?
Usually not. Accept them and normalise to lowercase for storage.
Is the nil UUID valid?
It's a valid UUID format with a special meaning. Whether to accept it depends on your application.
Summary
Choose a validation policy, enforce it with a strict regex or a parser plus canonical comparison, normalise what you store, and remember that format validation isn't authorisation.
Related tools
Sources
- uuid (npm package) – uuidjs (opens in a new tab)
- uuid — UUID objects according to RFC 9562 – Python documentation (opens in a new tab)
Related articles
- UUID Regex PatternsTested regex patterns for UUIDs, from loose format checks to strict version and variant validation, with examples.
- Why Is My UUID Invalid?The usual reasons a UUID gets rejected, from invisible whitespace to truncation, and how to fix each.
- Generate a UUID in JavaScriptcrypto.randomUUID() in browsers and Node.js, the uuid package for other versions, and why Math.random() snippets are a bad idea.