javascriptnode.jsuuidtimeuuid

Validating TimeUuid using JavaScript (Node.js)


I would like to validate a uuid string to make sure it's a valid time uuid (i.e. a test to check if a string is a time uuid).

For example: A request comes in with an id like so, as a string: 54d890dc-40a5-4686-8d7e-095e3934d99e (this is uuid v4), is there any way to test whether this uuid is a time uuid (v1) or not (uuid v4)?


Solution

  • You can use regexp :

    For example

    const index = [
        // UUID v1:
        /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
        // UUID v2:
        /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
        // UUID v3:
        /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
        // UUID v4:
        /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
       //UUID v5:
       /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    ].findIndex(x => x.test(stringToTest));
    
    console.log(index === -1 ? 'Unknown UUID' : `UUID version ${index + 1}`);
    

    Here about UUID regexp