I am working on an API. For a better developer experience, I would like to report back to the user any easily-found issue with params
. My code validates strings, integers, booleans, iso8601 dates, and domain specific list of values. I am looking into a way to validate if a string is a valid UUID. I am looking into possible options to do it.
A valid UUID should have 5 sections separated by a dash ( - ) and in the first section it should have 8 characters, the second, third, and the fourth section should have 4 characters each, and the last section should have 12 characters with a total of 32 characters.
Format. In its canonical textual representation, the 16 octets of a UUID are represented as 32 hexadecimal (base-16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 hexadecimal characters and 4 hyphens). For example: 123e4567-e89b-12d3-a456-426614174000.
Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8 , 9 , A , or B . Before performing the regex, I might add a quick simple IF() to test if the length of the string is 32 or 36 characters long. If not, it's not a UUID hex string.
Ruby | Random uuid() function Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier).
Based on the prevalent suggestion to use regex:
def validate_uuid_format(uuid)
uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
return true if uuid_regex.match?(uuid.to_s.downcase)
log_and_raise_error("Given argument is not a valid UUID: '#{format_argument_output(uuid)}'")
end
Please note that, this only checks if a string adheres to a 8-4-4-4-12
format and ignores any version checks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With