NodeJS UUID Validate

To validate UUID (GUID) in NodeJS, we can use below options:

  1. UUID NPM Package
  2. We can write our own custom regular expressions to validate.

1. UUID NPM Package

To use UUID package, we can use below command to include in our project.

NodeJS Install UUID Package

To validate UUID in NodeJS, we can use validate method of UUID package. Below is the sample code.


const uuid = require('uuid');

const uniqueId = "3112b3db-c1ef-4cc2-994b-306d75834277";

const isValid = uuid.validate(uniqueId); //return true as Valid, false as Invalid

In the first line, we are importing UUID NPM package. In second line, we are declaring a custom uuid number. In the third line, we are validating UUID with the help of validate method. This method returns “true”, if the uuid is valid else returns false.

With the help of UUID package, we can check the version of the UUID. A UUID can have different versions from 1 to 5. To check the version of UUID, we can use version() method of UUID package. Below is the code.


const uuidVersion = uuid.version(uniqueId);

2. Custom regular expressions to Validate UUID

We can write different regular expressions to validate different versions of UUID. Below are the options:


v1: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

v2: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[2][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

v3: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[3][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

v4: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[4][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

v5: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[5][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

To validate, use test method as shown below. we are validating version 4 uuid.


const isValid = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[4][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i.test('3112b3db-c1ef-4cc2-994b-306d75834277')

To use a common regular expression to validate any version of UUID. Use below regular expression.

v1-v5: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i

In the below example, we are validating version 1 uuid.


const isValid = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89AB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i.test('3112b3db-c1ef-1cc2-994b-306d75834277')

Summary

To validate UUID in NodeJS, we can either use NPM UUID package or use custom regular expressions. We can validate any version of UUID easily.Â