View Source Skema (Skema v0.2.2)

Skema is a simple schema validation and casting library for Elixir. Skema provide 3 main APIs:

  1. Skema.cast_and_validate/2 for casting and validating data with given schema
  2. Skema.cast/2 for casting data with given schema
  3. Skema.validate/2 for validating data with given schema

Define schema

Skema schema could be a map with field name as key and field definition as value or a schema module.

schema = %{
  email: [type: :string, required: true],
  age: [type: :integer, number: [min: 18]],
  hobbies: [type: {:array, :string}]
}

or

defmodule UserSchema do
  use Skema

  defschema do
    field :email, :string, required: true
    field :age, :integer, number: [min: 18]
    field :hobbies, {:array, :string}
  end
end

Use schema

You can use schema to cast and validate data like this

data = %{email: "blue", age: 10, hobbies: ["swimming", "reading"]}
schema = %{
  email: [type: :string, required: true],
  age: [type: :integer, number: [min: 18]],
  hobbies: [type: {:array, :string}]
}

case Skema.cast_and_validate(data, schema) do
  {:ok, data} -> IO.puts("Data is valid")
  {:error, errors} -> IO.puts(inspect(errors))
end

What is the difference between APIs error

Summary

Functions

Cast data with given schema.

Cast and validate data with given schema.

Validate data with given schema.

Functions

@spec cast(data :: map(), schema :: map() | module()) ::
  {:ok, map()}
  | {:error,
     %Skema.Result{
       errors: term(),
       params: term(),
       schema: term(),
       valid?: term(),
       valid_data: term()
     }}

Cast data with given schema.

Link to this function

cast_and_validate(data, schema)

View Source
@spec cast_and_validate(data :: map(), schema :: map() | module()) ::
  {:ok, map()} | {:error, errors :: map()}

Cast and validate data with given schema.

Link to this function

cast_array(type, value, acc \\ [])

View Source
@spec validate(data :: map(), schema :: map() | module()) ::
  :ok
  | {:error,
     %Skema.Result{
       errors: term(),
       params: term(),
       schema: term(),
       valid?: term(),
       valid_data: term()
     }}

Validate data with given schema.