Skip to content

Instantly share code, notes, and snippets.

@bugventure
Last active November 30, 2021 10:16
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bugventure/f71337e3927c34132b9a to your computer and use it in GitHub Desktop.
Save bugventure/f71337e3927c34132b9a to your computer and use it in GitHub Desktop.
UUID regex matching in node.js
function createUUID() {
return uuid.v4();
}
// version 4
// createUUID.regex = '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$';
createUUID.regex = '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$';
createUUID.is = function (str) {
return new RegExp(createUUID.regex).test(str);
};
@Alex-Werner
Copy link

If I may drop a line (as this link is the first answer on google for "uuid v4 regex javascript") :

In third block of v4 UUID's, the first char have to start with a 4.
The fourth block have it's first char who can be either 8-9-a or b.

So shouldn't it be something like ?:
var uuidV4Regex = '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4{1}[a-fA-F0-9]{3}-[89abAB]{1}[a-fA-F0-9]{3}-[a-fA-F0-9]{12}$';

@jakewtaylor
Copy link

jakewtaylor commented Oct 25, 2017

This matches xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where x is any hex digit, and Y is any hex digit from 8 to B (89AB).

I think this is as short as you can get the RegEx, but please let me know if this can get shorter.

const uuidV4Regex = /^[A-F\d]{8}-[A-F\d]{4}-4[A-F\d]{3}-[89AB][A-F\d]{3}-[A-F\d]{12}$/i;
// compared to:     /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4{1}[a-fA-F0-9]{3}-[89abAB]{1}[a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/

const isValidV4UUID = uuid => uuidV4Regex.test(uuid);

/*
 * isValidV4UUID('36e255d0-3356-4418-a2be-3024fff9ea7f') => true
 *
 * isValidV4UUID('b39840b1-d0ef-446d-e555-48fcca50a90a') => false
 *                                   ^ is not between 8 and B
 *
 * isValidV4UUID('683367ed-ed5d-228b-8041-e4bf2d4b4476') => false
 *                              ^ is not 4
 *
 * isValidV4UUID('4cf3i040-ea14-4daa-b0b5-ea9329473519') => false
 *                    ^ is not hex
 */

@vcgato29
Copy link

Thank You Same Requester

@jvalentik
Copy link

👍

@knurherb
Copy link

:D

@prodis
Copy link

prodis commented Jun 12, 2019

👍

@mattstabeler
Copy link

To use this in an express route

/:uuid([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})/

like

router.get(`/path/:uuid([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})/path`, 
    (req, res, next) => {
       const uuiid = req.params.uuid;
    }) {
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment