How to Validate a UUID with Regular Expressions in JavaScript
Let’s see how we can validate UUIDv4 using regular expressions in JavaScript.
Suppose we’re using the uuid
npm package to generate a UUID.
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // '2808f161-0f83-4382-8d50-37530fcc9dbe'
If you want to randomly generate a UUID online, check out uuidtools.com.
1. Create a regular expression to match UUIDv4
A UUID is a 36 character string containing 32 hexadecimal characters and 4 hyphens.
Below is a regular expression that will match a Version 4 UUID.
const regex = /^[a-z,0-9,-]{36}$/;
^
matches the beginning of the input[a-z,0-9,-]
matches lowercase letters, numbers, and hyphens{36}
requires the length to be36
characters$
matches the end of the input
If the location of the hyphens needs to follow the standard UUIDv4 format, you can use the following regular expression:
const regex = /^[a-z,0-9]{8}-[a-z,0-9]{4}-4[a-z,0-9]{3}-[89AB][a-z,0-9]{3}-[a-z,0-9]{12}$/;
2. Validate a UUID using regular expression
We can easily validate a UUID using the test()
method, which matches some input string against a regular expression literal.
function isValidUuid(str) {
const regex = /^[a-z,0-9,-]{36}$/;
return regex.test(str)
}
If you’re curious about the regex, I’d recommend using regex101.com to investigate and test regular expressions.