2022-07-11

1657512000
guides
 11 Jul 2022  guides

Validating UUIDs with Regular Expressions in JavaScript

Since the Crypto API is now standard in all browser engines, generating a UUID is as simple as invoking the crypto.randomUUID() method in order to return a 36 character v4 UUID using a cryptographically secure random number generator:

let uuid = crypto.randomUUID();
console.log(uuid); // "abc861e3-9ac3-4f82-ab72-9926ca4716e4"

However, there isn’t a corresponding method to validate a UUID’s format out of the box. Since error checking is always desirable when working with situations where UUIDs are present, a simple Regular Expression pattern can be used to achieve this.

Creating the Regular Expression

Using a regular expression literal, we can gradually include the patterns that will match the character set and length of a UUID. First, we can create the expression by including the lowercase alphabet:

let regex = /[a-z]/;

Then, we add numbers:

let regex = /[a-z,0-9]/;

Next we have to include the dash - delimiter that’s found multiple times in the UUID sequence:

let regex = /[a-z,0-9,-]/;

We can then include the length parameter. This is in the format {a,b} where a is the minimum length and b the maximum length; hence the pattern is forced to match a 36-character long string:

let regex = /[a-z,0-9,-]{36,36}/;

While this covers the contents and length of the pattern, the actual start and end have to be defined before the pattern can be matched.

The caret assertion ^ matches the beginning of input, while the dollar sign assertion $ matches the end of input:

let regex = /^[a-z,0-9,-]{36,36}$/;

Testing the Regular Expression

While a validation method isn’t available using crypto, there is a test method that will compare a string of text against a regular expression literal, returning a Boolean.

We can therefore generate a UUID and test it’s validity using the expression we’ve just made:

let uuid = crypto.randomUUID();

let regex = /^[a-z,0-9,-]{36,36}$/;

console.log(regex.test(uuid)); // true

You can also test it in an online RegExp tool such as regex101.com, the result of which looks like this:

I hope you found this information helpful, as working with UUIDs comes in handy when dealing with use cases such as user authentication/authorization, unique URLs, etc.

Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

[ this node is permanently morphing last updated on 28 May 2023 ]

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems