Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate UUID string in ruby/rails

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.

like image 443
bunufi Avatar asked Nov 27 '17 10:11

bunufi


People also ask

How do you check if a string is a UUID?

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.

What does a valid UUID look like?

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.

How do I find my UUID v4?

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.

What is UUID in Ruby?

Ruby | Random uuid() function Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier).


1 Answers

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.

like image 89
bunufi Avatar answered Sep 17 '22 22:09

bunufi