UUID v4 Validation
Validates a UUID version 4 (randomly generated) in standard hyphenated format.
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iHow it works
UUID v4 is randomly generated. The version digit is always 4 (third group starts with 4), and the variant bits are 8, 9, a, or b (fourth group starts with one of these). This pattern enforces both constraints along with the standard 8-4-4-4-12 hyphenated format.
Test Cases
Should Match
- 550e8400-e29b-41d4-a716-446655440000
- f47ac10b-58cc-4372-a567-0e02b2c3d479
Should NOT Match
- 550e8400e29b41d4a716446655440000
- not-a-uuid
- 550e8400-e29b-31d4-a716-446655440000
Quick Summary
Validates UUID v4 strings in the standard 8-4-4-4-12 hyphenated format. Enforces the version 4 marker (third group starts with 4) and the RFC 4122 variant bits (fourth group starts with 8, 9, a, or b).
Key Takeaways
- UUID v4 format: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx
- The 4 in the third group identifies the UUID version
- The [89ab] in the fourth group identifies the RFC 4122 variant
- Case-insensitive flag (i) allows both uppercase and lowercase hex digits
When to use it
- Validating IDs from external APIs before database insertion
- Checking URL path parameters that should be UUIDs
- Sanitizing user-submitted resource identifiers
Common Mistakes
- Using this to validate UUID v1, v5, or v7, the version digit differs
- Forgetting the case-insensitive flag, UUIDs are often returned in uppercase
- Treating UUID validation as a security check, UUIDs are not secret tokens
UUID v4 Validation, Frequently Asked
What is the difference between UUID v4 and v7?
UUID v4 is fully random. UUID v7 is time-ordered (first 48 bits are a Unix timestamp), making it sortable and better for database primary keys.
How do I generate a UUID v4 in JavaScript?
Use crypto.randomUUID() in Node.js 14.17+ or browsers, or the 'uuid' npm package: import { v4 as uuidv4 } from 'uuid'.