Last active
August 1, 2024 22:54
-
-
Save bugventure/f71337e3927c34132b9a to your computer and use it in GitHub Desktop.
UUID regex matching in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
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
*/
Thank You Same Requester
๐
:D
๐
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
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}$';