Contrak

Schema and contract validation library for Elixir

Build StatusCoverage StatusHex Versiondocs

This library is best suited for validating compicated params contract/schema passing to your function. For example when you build a client library that call 3rd API and you want to make sure all parameters are valid before processing. If you want to cast external data to your internal schema, take a look at Tarams

Installation

Adding contrak to your list of dependencies in mix.exs:

def deps do
  [
    {:contrak, "~> 0.1.1"}
  ]
end

Documentation here https://hexdocs.pm/contrak.

Usage

Contrak helps to validate data with given schema:

  task_schema = %{
    title: [type: :string, required: true, length: [min: 20]],
    description: :string,
    tag: [type: {:array, :string}, default: []]
    point: [type: :integer, number: [min: 0]],
    due_date: [type: NaiveDateTime, default: &seven_day_from_now/0] ,
    assignee: [type: {:array, User}, required: true],
    attachments: [
      type: %{
         name: [type: :string, required: true],
         url: :string
       }
    ]
  }

  case Contrak.validate(data, task_schema) do
    {:ok, valid_data} ->
        # do your logic

    {:error, errors} ->
        IO.inspect(errors)
  end

Contrak also do:

NOTES: Contract only validate data, not cast data

Schema definition

Contrak provide a simple schema definition:

<field_name>: [type: <type>, required: <true|false>, default: <value|function>, [...validation]]

  %{
    product_name: [type: :string, required: true, length: [min: 20]],
    sku: [type: :string, required: true],
    selling_price: [type: :integer, required: true, number: [min: 0]]
    state: [type: :string, default: "draft"]
  }

Shorthand form if you only check for type:

<field_name>: <type>

  %{
    product_name: :string,
    sku: :string,
    price: :integer
  }

For more details, please check document for Contrak.Schema

Validations

Contrak uses Valdi to validate data. So you can use all validation from Valdi. This is list of available validation for current version of Valdi:

Please check Valdi document for more details