How to Test Valid UUID or GUID in javascript

This tutorial explains how to check given UUID or GUID is a valid string

UUIDs format follows RFC4122 specification.

Check Valid GUID in plain javascript

Valid UUID satisfies the below conditions

  • UUID contains 32 characters hexa string, separated by a hyphen
  • every Character is a Hexa decimal
  • String is the format of 8-4-4-4-12 strings separated with a hyphen

Plain Javascript condition check for UUID example

// checks given character is Hexa decimal character
const isHexaCharacter = (character) => "0123456789abcdef".includes(character.toLowerCase());
// checks given string is valid UUID
const isValidUUID = (input) => {
  // replace the hyphen with space
  input = input.replaceAll("-", ");
  // check input length is 32, and each character is hexa decimal
  return input.length === 32 && [...input].every(isHexaCharacter);

console.log(isValidUUID("abc"));  // false
console.log(isValidUUID("8336b1c6-59e7-4ac7-a0f6-0a80a38ef6a6"));  // true
console.log(isValidUUID("KLM"));   // false
console.log(isValidUUID(""));   // false

Another way is to check using regular expressions using the 8-4-4-4-12 string.

Check valid UUID in Nodejs

Node has a uuid package which provides multiple functions to generate different versions of UUID and also validate function to check whether given uuid is valid or not

validate functions checks for given uuid is valid as per all versions.

const { v4: uuidv4, validate } = require("uuid");
const uuidString = "8336b1c6-59e7-4ac7-a0f6-0a80a38ef6a6";
console.log(validate(uuidString)); // true
console.log(validate("1abc")); // false
console.log(validate(" ")); // false


Multiple options are listed above,choose based on your needs.