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:
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:
Then, we add numbers:
Next we have to include the dash -
delimiter that’s found multiple times in the UUID sequence:
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:
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:
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:
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.
Links
- Regular Expressions - developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
- UUID v4 Pattern - regex101.com/r/jINXQp/1