Zoi
is a schema validation library for Elixir, designed to provide a simple and flexible way to define and validate data.
zoi
to your list of dependencies in mix.exs
:
def deps do
[
{:zoi, "~> 0.5"}
]
end
You can define schemas and validate data against them. Schemas can be used to validate maps, lists or primitive types such as strings, integers, etc.
# Define a schema with a string type
iex> schema = Zoi.string() |> Zoi.min(3)
iex> Zoi.parse(schema, "hello")
{:ok, "hello"}
iex> Zoi.parse(schema, "hi")
{:error, [%Zoi.Error{message: "too small: must have at least 3 characters"}]}
# Add transforms to a schema
iex> schema = Zoi.string() |> Zoi.trim()
iex> Zoi.parse(schema, " world ")
{:ok, "world"}
# Validate a structured data in a map
iex> schema = Zoi.object(%{name: Zoi.string(), age: Zoi.integer(), email: Zoi.email()})
iex> Zoi.parse(schema, %{name: "John", age: 30, email: "john@email.com"})
{:ok, %{name: "John", age: 30, email: "john@email.com"}}
iex> Zoi.parse(schema, %{email: "invalid-email"})
{:error, [
%Zoi.Error{path: [:name], message: "is required"},
%Zoi.Error{path: [:age], message: "is required"},
%Zoi.Error{path: [:email], message: "invalid email format"}
]}
And many more possibilities, including nested schemas, custom validations and data transformations. Check the official docs for more details.
Zoi
is inspired by Zod and Joi, providing a similar experience for Elixir.