Skip to content
SimpleTools24

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.

Decide What "Valid" Means

Before writing code, pick a policy:

Validation policies for UUID input
PolicyAcceptsGood for
Canonical onlyLowercase, hyphenated 8-4-4-4-12APIs with strict contracts
Standard, any caseUpper or lower case, hyphenatedMost web forms and APIs
LenientBraces, no hyphens, urn:uuid: prefixImport tools, admin consoles
Version-specificOnly v4, or only v7Rarely 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

javascript
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

javascript
import { validate, version } from 'uuid';

validate('9b2c1f7e-5d3a-4c8b-a1e2-7f6d0c9b3a54'); // true
version('9b2c1f7e-5d3a-4c8b-a1e2-7f6d0c9b3a54');  // 4

The package's validate also accepts the nil and max UUIDs. Check its documentation for the exact rules in the version you install.

Normalising

javascript
const canonical = (s) => s.trim().toLowerCase().replace(/^\{|\}$/g, '');

Python

Parse and Catch

python
import uuid

def is_uuid(value: str) -> bool:
    try:
        uuid.UUID(value)
        return True
    except (ValueError, TypeError, AttributeError):
        return False

uuid.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

python
def is_canonical_uuid(value: str) -> bool:
    try:
        return str(uuid.UUID(value)) == value
    except (ValueError, TypeError, AttributeError):
        return False

Because str() produces lowercase hyphenated output, this only accepts the canonical form.

Checking the Version

python
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. Use Guid.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 uuid or uniqueidentifier column, 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 the uuid format, 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.UUID to parse and validate it automatically.
  • OpenAPI: type: string, format: uuid documents 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.

Sources