Lightning.Validators.Hex (Lightning v2.15.0-pre5)
View SourceFlexible validator for hex strings with configurable length.
By default it expects 12 lowercase hex characters (0-9, a-f), which
matches our common “head hash” format. You can change both the length
(fixed integer or inclusive range) and the letter case via options.
Length
Pass either:
- a positive integer (exact length), or
- an inclusive
Range(min..max length).
Case handling
Use the :case option:
:lower(default) – allow onlya-f:upper– allow onlyA-F:any– allowa-forA-F
Examples
iex> Lightning.Validators.Hex.valid?("deadbeefcafe")
true
iex> Lightning.Validators.Hex.valid?("DEADBEEFCAFE")
false
iex> Lightning.Validators.Hex.valid?("DEADBEEFCAFE", case: :upper)
true
iex> Lightning.Validators.Hex.valid?("a1", 1..2)
true
iex> Lightning.Validators.Hex.valid?("xyz", 3)
false
iex> Lightning.Validators.Hex.format()
~r/^[0-9a-f]{12}$/
iex> Lightning.Validators.Hex.format(8)
~r/^[0-9a-f]{8}$/
iex> Lightning.Validators.Hex.format(8..64, case: :any)
~r/^[0-9A-Fa-f]{8,64}$/Ecto usage
changeset
|> Ecto.Changeset.validate_format(:hash, Lightning.Validators.Hex.format())
Summary
Types
Case handling for hex letters.
Length can be a positive integer (exact) or an inclusive range.
Functions
Returns a compiled Regex for hex strings.
Returns true if s is hex of the requested length and case.
Types
@type case_opt() :: :lower | :upper | :any
Case handling for hex letters.
@type length_spec() :: pos_integer() | Range.t()
Length can be a positive integer (exact) or an inclusive range.
Functions
@spec format() :: Regex.t()
Returns a compiled Regex for hex strings.
Accepts convenience forms:
format()— default length (12), lowercaseformat(len_or_range)— custom length, lowercaseformat(case: :upper | :any)— default length with custom caseformat(len_or_range, opts)— full control
@spec format(length_spec()) :: Regex.t()
@spec format(keyword()) :: Regex.t()
@spec format( length_spec(), keyword() ) :: Regex.t()
Returns true if s is hex of the requested length and case.
Accepts convenience forms:
valid?(s)— uses default length (12) andcase: :lowervalid?(s, len_or_range)— custom length, lowercase onlyvalid?(s, case: :upper | :any)— default length with custom casevalid?(s, len_or_range, opts)— full control
@spec valid?(term(), length_spec(), keyword()) :: boolean()