Validating a UUID in JavaScript means confirming a string matches the canonical 8-4-4-4-12 hexadecimal format and, optionally, a specific version. You can do this with a regular expression or with the uuid package.
Both approaches are shown below, including how to extract the version digit.
Validate with a regular expression
This pattern accepts any RFC 4122 / RFC 9562 UUID (versions 1-8) with the correct variant bits. It is case-insensitive.
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isUuid(value) {
return UUID_RE.test(value);
}
console.log(isUuid("36b8f84d-df4e-4d49-b662-bcde71a8764f")); // true
console.log(isUuid("hello")); // falseValidate with the uuid package
The uuid package exposes validate() and version() helpers, which avoid hand-written regexes and stay correct as new versions are added.
import { validate as uuidValidate, version as uuidVersion } from "uuid";
const value = "36b8f84d-df4e-4d49-b662-bcde71a8764f";
console.log(uuidValidate(value)); // true
console.log(uuidValidate(value) && uuidVersion(value)); // 4Frequently asked questions
- What is a good UUID validation regex?
- Use /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, which enforces the version and variant bits.
- How do I check the UUID version in JavaScript?
- Use the version() helper from the uuid package, or read the first character of the third group in the string.
- Should I validate UUIDs with a regex or a library?
- A regex is fine for format checks. The uuid package’s validate() is more future-proof because it tracks the spec as new versions are standardised.
