View Source Skema (Skema v0.2.2)
Skema is a simple schema validation and casting library for Elixir. Skema provide 3 main APIs:
Skema.cast_and_validate/2
for casting and validating data with given schemaSkema.cast/2
for casting data with given schemaSkema.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
Skema.cast_and_validate/2
will return error if there is any error in casting or validating dataSkema.cast/2
will return error for casting data only (data can be casted to proper type or not)Skema.validate/2
will return error for validating data only
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.
@spec cast_and_validate(data :: map(), schema :: map() | module()) :: {:ok, map()} | {:error, errors :: map()}
Cast and validate data with given schema.
@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.