โ† Back to Blog

How to Validate a UUID String

2026-04-11 ยท 5 min read

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 โ†’