xema v0.1.1 Xema View Source

A schema validator inspired by JSON Schema

Link to this section Summary

Types

t()

The Xema base struct contains the meta data of a schema

The available type notations

The keywords for the schema types

Link to this section Types

Link to this type t() View Source
t() :: %Xema{description: String.t() | nil, id: String.t() | nil, keywords: term(), schema: String.t() | nil, title: String.t() | nil, type: types()}

The Xema base struct contains the meta data of a schema.

  • id a unique idenfifier.
  • schema declares the used schema.
  • title of the schema.
  • description of the schema.
  • type contains the specification of the schema.
Link to this type type() View Source
type() ::
  nil |
  :any |
  :boolean |
  :map |
  :list |
  :string |
  :number |
  :float |
  :integer

The available type notations.

Link to this section Functions

Link to this function is_valid?(xema, value) View Source
is_valid?(Xema.t(), any()) :: boolean()
Link to this function validate(xema, value) View Source
validate(Xema.t(), any()) :: :ok | {:error, any()}
Link to this function xema(type, keywords \\ []) View Source
xema(type(), keyword()) :: Xema.t()

This function defines the schemas.

The first argument sets the type of the schema. The second arguments contains the ‘keywords’ of the schema.

Parameters

  • type: type of the schema.
  • opts: keywords of the schema.

Examples

iex> import Xema
Xema
iex> xema :string, min_length: 3, max_length: 12
%Xema{
  type: %Xema.String{
    max_length: 12,
    min_length: 3,
  }
}

For nested schema you can use {:type, opts: ...} like here.

Examples

iex> import Xema
Xema
iex> schema = xema :list, items: {:number, minimum: 2}
%Xema{
  type: %Xema.List{
    items: %Xema.Number{
      minimum: 2
    }
  }
}
iex> validate(schema, [2, 3, 4])
:ok
iex> validate(schema, [2, 3, 1])
{:error,
  %{
    reason: :invalid_item,
    at: 2,
    error: %{
      minimum: 2,
      reason: :too_small
    }
  }
}