How to Validate a UUID String
Standard UUID Format Rules
A valid UUID must meet these format requirements: total length of 36 characters; composed of 5 groups separated by hyphens (-) in the format 8-4-4-4-12 (hex character count per group); can only contain hexadecimal characters (0-9 and a-f, case insensitive) and hyphens; the first character of the third group is the version number (1-7, corresponding to UUID versions 1 through 7); the first character of the fourth group is the variant identifier (8, 9, a, or b corresponding to RFC 4122 variant). Typical valid UUID: 550e8400-e29b-41d4-a716-446655440000.
Regular Expression Validation
# ๅฎฝๆพๆจกๅผ๏ผๅชๆฃๆฅๆ ผๅผ๏ผไธๆฃๆฅ็ๆฌๅๅไฝ๏ผ
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$
# ไธฅๆ ผๆจกๅผ๏ผๆฃๆฅๆ ผๅผ + ็ๆฌ 1-7 + RFC 4122 ๅไฝ๏ผ
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-7][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
# ๅชๆฅๅ UUID v4๏ผๆๅธธ็จ๏ผ
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
# ๅ
จๅฐๅไธฅๆ ผๆ ผๅผ๏ผRFC 4122 ๆจ่๏ผ
^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$
Validation Implementation in Various Languages
# Python
import uuid, re
def validate_uuid(s: str) -> bool:
"""ไฝฟ็จๆ ๅๅบ้ช่ฏ UUID"""
try:
uuid.UUID(s)
return True
except ValueError:
return False
def validate_uuid_v4(s: str) -> bool:
"""้ช่ฏๆฏๅฆๆฏ UUID v4"""
try:
u = uuid.UUID(s)
return u.version == 4
except ValueError:
return False
# JavaScript / TypeScript
function isUUID(str) {
const pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return pattern.test(str);
}
// Java
import java.util.UUID;
static boolean isUUID(String s) {
try { UUID.fromString(s); return true; }
catch (IllegalArgumentException e) { return false; }
}
// Go
import "regexp"
var uuidRegex = regexp.MustCompile(
`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-7][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`,
)
func isUUID(s string) bool { return uuidRegex.MatchString(s) }
Extracting Version Information from UUID
# Python๏ผไป UUID ๅญ็ฌฆไธฒๆๅ็ๆฌ
import uuid
def get_uuid_version(uuid_str: str) -> int:
try:
u = uuid.UUID(uuid_str)
return u.version
except ValueError:
return -1 # ้ๆณๆ ผๅผ
# ็ดๆฅไปๅญ็ฌฆไธฒๆๅ๏ผไธ่งฃๆๅฏน่ฑก๏ผ
def get_uuid_version_fast(uuid_str: str) -> str:
"""ไปๅญ็ฌฆไธฒ็ฌฌ15ไฝ๏ผ0-indexed๏ผ่ฏปๅ็ๆฌ"""
if len(uuid_str) == 36 and uuid_str[14] in '1234567':
return uuid_str[14]
return 'unknown'
# ็คบไพ
ids = [
'550e8400-e29b-11d4-a716-446655440000', # v1
'550e8400-e29b-41d4-a716-446655440000', # v4
'550e8400-e29b-71d4-a716-446655440000', # v7
]
for uid in ids:
print(f"{uid}: version {get_uuid_version(uid)}")
Handling UUID Variant Formats
In practice, you may encounter multiple UUID format variants that need validation or normalization: GUID format with braces ({550e8400-e29b-41d4-a716-446655440000}); compact format without hyphens (550e8400e29b41d4a716446655440000); uppercase format (550E8400-E29B-41D4-A716-446655440000). Best practice for normalizing these formats: first remove braces, normalize to lowercase, check length (36 chars with hyphens, 32 without), then validate format. Python's uuid.UUID() constructor accepts all these variants and automatically normalizes.
Validating UUID Path Parameters in APIs
# FastAPI / Python ่ชๅจ้ช่ฏ
from uuid import UUID
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def get_item(item_id: UUID):
# FastAPI ่ชๅจ้ช่ฏ item_id ๆ ผๅผ๏ผๆ ผๅผ้่ฏฏ่ฟๅ 422
return {"id": str(item_id)}
# Express / Node.js ไธญ้ดไปถ้ช่ฏ
const { validate: isUuid } = require('uuid');
function validateUUIDParam(req, res, next) {
const { id } = req.params;
if (!isUuid(id)) {
return res.status(400).json({
error: 'Invalid UUID format',
received: id
});
}
next();
}
app.get('/users/:id', validateUUIDParam, (req, res) => {
// ๆญคๅค req.params.id ๆฏๅๆณ UUID
});
Nil UUID and Special UUIDs
Several special UUID values are worth knowing: Nil UUID (all zeros: 00000000-0000-0000-0000-000000000000) is the "empty" UUID defined by RFC 4122, similar to null, typically used to represent "no ID"; Max UUID (all F's: ffffffff-ffff-ffff-ffff-ffffffffffff) is the maximum UUID defined by RFC 9562. In validation, if your business does not accept Nil UUID, add an extra check: ensure the string is not all zeros. Some systems use Nil UUID as a default value and need special handling.
Try the free tool now
Use Free Tool โ