Last active
May 4, 2017 09:55
-
-
Save ratpik/d9657e1b62b0a52c5a3a019b39d041f2 to your computer and use it in GitHub Desktop.
Checks if input is a valid UUID (any version, includes nil and GUID) as per RFC 4122 - https://tools.ietf.org/html/rfc4122
This file contains 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
// Fiddle - https://jsfiddle.net/ratpik/azf5a9bv/3/ | |
var UUIDIndex = {0:8, 1:4, 2:4, 3:4, 4:12}; | |
function isHex(h, index) { | |
if (UUIDIndex[index] !== _.size(h)) return false; | |
var a = parseInt(h, 16); | |
return !isNaN(a) && | |
a.toString(16) === _.toLower(h) || | |
_.join(_.times(_.size(h), _.constant(0)), '') === _.toLower(h); | |
} | |
//All UUIDs are of the format 8-4-4-4-12 | |
function isValidUUID(id) { | |
return id && | |
(id = id.split('-')) && | |
id.length === 5 && | |
_.chain(id) | |
.map(isHex) | |
.reduce(function (isHex, result) { return (result = result && isHex); }) | |
.value(); | |
} | |
//The different UUID versions only differ in the way they are generated | |
//true - Version 1 UUID (Timestamp and MAC) | |
console.log(isValidUUID('aba8a19c-2ff0-11e7-93ae-92361f002671')); | |
//true - Version 4 UUID (Pseudorandom) | |
console.log(isValidUUID('a4df3fd6-ac7a-499f-9575-a5a5411a6ce7')); | |
//true - nil UUID | |
console.log(isValidUUID('00000000-0000-0000-0000-000000000000')); | |
//true - Microsoft GUID | |
console.log(isValidUUID('d5fdb8ce-4864-4f18-ad52-1f664a1689b5')); | |
//false | |
console.log(isValidUUID('123e4567')); | |
//false - Looks like GUID | |
console.log(isValidUUID('d5fdb8ce-4864-4h18-ad52-1f664a1689b5')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment