Lightning.Validators.Hex (Lightning v2.14.5-pre1)

View Source

Flexible 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 only a-f
  • :upper – allow only A-F
  • :any – allow a-f or A-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

case_opt()

@type case_opt() :: :lower | :upper | :any

Case handling for hex letters.

length_spec()

@type length_spec() :: pos_integer() | Range.t()

Length can be a positive integer (exact) or an inclusive range.

Functions

format()

@spec format() :: Regex.t()

Returns a compiled Regex for hex strings.

Accepts convenience forms:

  • format() — default length (12), lowercase
  • format(len_or_range) — custom length, lowercase
  • format(case: :upper | :any) — default length with custom case

  • format(len_or_range, opts) — full control

format(opts)

@spec format(length_spec()) :: Regex.t()
@spec format(keyword()) :: Regex.t()

format(len_or_range, opts)

@spec format(
  length_spec(),
  keyword()
) :: Regex.t()

valid?(s)

@spec valid?(term()) :: boolean()

Returns true if s is hex of the requested length and case.

Accepts convenience forms:

  • valid?(s) — uses default length (12) and case: :lower
  • valid?(s, len_or_range) — custom length, lowercase only
  • valid?(s, case: :upper | :any) — default length with custom case

  • valid?(s, len_or_range, opts) — full control

valid?(s, opts)

@spec valid?(term(), length_spec()) :: boolean()
@spec valid?(
  term(),
  keyword()
) :: boolean()

valid?(s, len_or_range, opts)

@spec valid?(term(), length_spec(), keyword()) :: boolean()