JAVASCRIPT
Validating UUID v4 Format with Regex
Learn to validate if a string conforms to the standard UUID v4 format (e.g., xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) using a precise regular expression.
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;
console.log(uuidv4Regex.test("f47ac10b-58cc-4372-a567-0e02b2c3d479")); // Output: true
console.log(uuidv4Regex.test("f47ac10b-58cc-4372-g567-0e02b2c3d479")); // Output: false (invalid character 'g')
console.log(uuidv4Regex.test("f47ac10b-58cc-5372-a567-0e02b2c3d479")); // Output: false (invalid version '5')
console.log(uuidv4Regex.test("short-uuid")); // Output: false
How it works: This JavaScript snippet uses a regex to validate the format of a UUID v4. The pattern `^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$` ensures the string starts and ends (`^` and `$`) with the correct structure: eight, four, four, four, and twelve hexadecimal characters, separated by hyphens. The `4` in the third group specifically validates UUID version 4, and `[89ab]` validates the variant in the fourth group. The `i` flag makes the match case-insensitive for hex characters.