isUUIDv4
Checks if a string is a valid UUID v4.
1/**
2 * Checks if a string is a valid UUID v4.
3 *
4 * @param value - The string to validate.
5 * @returns True if the string is a valid UUID v4, false otherwise.
6 */
7export function isUUIDv4(value: string): boolean {
8 const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9 return uuidV4Regex.test(value);
10}
Strict UUID v4 Format Enforcement
The regular expression explicitly checks for version 4 UUIDs (with a "4" in the third block and "[89ab]" in the fourth), ensuring precise validation.
Case-Insensitive Matching
Supports uppercase and lowercase hexadecimal characters via the
i
flag for flexibility in input.Lightweight and Dependency-Free
Does not rely on external libraries like
uuid
orvalidator
, making it portable and fast.Reliable Input Filtering
Prevents malformed UUIDs from slipping through, which is crucial for database keys, API parameters, and security contexts.
Tests | Examples
1test('returns true for valid UUID v4', () => {
2 expect(isUUIDv4('550e8400-e29b-41d4-a716-446655440000')).toBe(true);
3 expect(isUUIDv4('f47ac10b-58cc-4372-a567-0e02b2c3d479')).toBe(true);
4});
5
6test('returns false for invalid UUID format', () => {
7 expect(isUUIDv4('550e8400-e29b-11d4-a716-446655440000')).toBe(false); // wrong version
8 expect(isUUIDv4('550e8400e29b41d4a716446655440000')).toBe(false); // no dashes
9 expect(isUUIDv4('')).toBe(false);
10});
11
12test('returns false for non-string inputs', () => {
13 expect(isUUIDv4(null as any)).toBe(false);
14 expect(isUUIDv4(undefined as any)).toBe(false);
15 expect(isUUIDv4(123 as any)).toBe(false);
16});
Common Use Cases
Validating API Request Parameters
Confirm that route or query parameters expected to be UUIDs are properly formatted.
Form Input Validation
Check if user-provided identifiers are valid UUID v4 values before submission.
Database Record Lookup
Ensure that IDs used for querying records follow the UUID v4 standard.
Filtering or Cleaning Incoming Data
Discard or flag invalid UUIDs in datasets or event payloads.
Generating Type Guards for TypeScript
Use it to narrow types in conditional checks when working with dynamic values.