Current section
Files
Jump to
Current section
Files
lib/uuid_helper.ex
defmodule BCUtils.UuidHelper do
@moduledoc """
Helper functions for working with UUIDs.
"""
@uuid_regex ~r/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@doc """
Validates if the given input is a valid UUID.
Accepts either a UUID string or a binary UUID.
## Examples
iex> UuidHelper.validate("550e8400-e29b-41d4-a716-446655440000")
true
iex> UuidHelper.validate("not-a-uuid")
false
iex> UuidHelper.validate(<<85, 14, 132, 0, 226, 155, 65, 212, 167, 22, 68, 102, 85, 68, 0, 0>>)
true
"""
@spec validate(String.t() | binary()) :: boolean()
def validate(uuid) when is_binary(uuid) do
case byte_size(uuid) do
16 ->
# Raw binary UUID (16 bytes)
true
36 ->
# String UUID format (8-4-4-4-12 = 36 chars)
uuid =~ @uuid_regex
_ ->
false
end
end
def validate(_), do: false
end