ToonEx.Options.Validator exception (toon_ex v1.1.0)

Copy Markdown View Source

Pure Elixir options validator to replace NimbleOptions.

Provides schema-based validation with support for common types, default values, and custom validation rules.

Summary

Functions

Returns a human-readable error message.

Validates options against a schema.

Types

option_config()

@type option_config() :: keyword()

schema_option()

@type schema_option() :: {atom(), option_config()}

t()

@type t() :: %ToonEx.Options.Validator{
  __exception__: true,
  key: atom(),
  message: String.t(),
  value: term()
}

validation_result()

@type validation_result() :: {:ok, keyword()} | {:error, t()}

Functions

message(validator)

Returns a human-readable error message.

validate(opts, schema)

@spec validate(
  keyword(),
  [schema_option()]
) :: validation_result()

Validates options against a schema.

Schema Configuration

Each option in the schema supports:

  • :type - Type specification (see supported types below)
  • :default - Default value if option is not provided
  • :required - Whether the option is required (default: false)
  • :doc - Documentation string (ignored during validation)

Supported Types

  • :any - Any value
  • :boolean - true or false
  • :atom - Any atom
  • :string - Binary string
  • :integer - Any integer
  • :pos_integer - Positive integer (> 0)
  • :non_neg_integer - Non-negative integer (>= 0)
  • :float - Float number
  • :number - Integer or float
  • :keyword - Keyword list
  • :list - List
  • :map - Map
  • {:in, values} - Value must be in the given list
  • {:or, types} - Value must match one of the given types
  • {:custom, fun} - Custom validation function

Examples

schema = [
  name: [type: :string, required: true],
  age: [type: :pos_integer, default: 0],
  role: [type: {:in, [:admin, :user]}, default: :user]
]

ToonEx.Options.Validator.validate([name: "Alice"], schema)
# => {:ok, [name: "Alice", age: 0, role: :user]}

ToonEx.Options.Validator.validate([age: -1], schema)
# => {:error, %ToonEx.Options.Validator{key: :name, ...}}