关于
Zoi 是一个 Elixir 模式验证库,可通过简单灵活的方式定义和验证数据。
开发工具实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- +1
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文Zoi
Zoi is a schema validation library for Elixir, designed to provide a simple and flexible way to define and validate data.
Sponsors
💜 If you or your company benefit from Zoi, consider becoming a sponsor. It helps keep the project active and benefits the Elixir ecosystem.
Installation
Add zoi to your list of dependencies in mix.exs:
def deps do
[
{:zoi, "~> 0.18"}
]
end
Usage
Zoi supports a wide range of types including string, integer, float, boolean, atom, date, datetime, decimal, array, tuple, map, keyword, enum, union, intersection, discriminated_union and more.
Parsing Data
Here's a simple example of how to use Zoi to validate a string:
iex> schema = Zoi.string() |> Zoi.min(3)
iex> Zoi.parse(schema, "hello")
{:ok, "hello"}
iex> Zoi.parse(schema, "hi")
{:error,
[
%Zoi.Error{
code: :greater_than_or_equal_to,
issue: {"too small: must have at least %{count} character(s)", [type: :string, count: 3]},
message: "too small: must have at least 3 character(s)",
path: []
}
]}
You can also apply transformations to your schema:
iex> schema = Zoi.string() |> Zoi.trim()
iex> Zoi.parse(schema, " world ")
{:ok, "world"}
You can also validate structured maps:
iex> schema = Zoi.map(%{name: Zoi.string(), age: Zoi.integer(), email: Zoi.email()})
iex> Zoi.parse(schema, %{name: "John", age: 30, email: "[email protected]"})
{:ok, %{name: "John", age: 30, email: "[email protected]"}}
iex> {:error, errors} = Zoi.parse(schema, %{email: "invalid-email"})
iex> Zoi.treefy_errors(errors)
%{name: ["is required"], email: ["invalid email format"], age: ["is required"]}
or arrays:
iex> schema = Zoi.array(Zoi.integer())
iex> Zoi.parse(schema, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> Zoi.parse(schema, [1, "2"])
{:error,
[
%Zoi.Error{
code: :invalid_type,
issue: {"invalid type: expected integer", [type: :integer]},
message: "invalid type: expected integer",
path: [1]
}
]}
or keywords:
iex> schema = Zoi.keyword(email: Zoi.email(), allow?: Zoi.boolean())
iex> Zoi.parse(schema, [email: "[email protected]", allow?: true])
{:ok, [email: "[email protected]", allow?: true]}
iex> Zoi.parse(schema, [allow?: "yes"])
{:error,
[
%Zoi.Error{
code: :invalid_type,
issue: {"invalid type: expected boolean", [type: :boolean]},
message: "invalid type: expected boolean",
path: [:allow?]
}
]}
And many more possibilities, including nested schemas, custom validations and data transformations. Check the official docs for more details.
Types
Zoi can infer types from schemas, allowing you to leverage Elixir's @type and @spec annotations for documentation
defmodule MyApp.Schema do
@schema Zoi.string() |> Zoi.min(2) |> Zoi.max(100)
@type t :: unquote(Zoi.type_spec(@schema))
end
This will generate the following type specification:
@type t :: binary()
This also applies to complex types, such as Zoi.map/2:
defmodule MyApp.User do
@schema Zoi.map(%{
name: Zoi.string() |> Zoi.min(2) |> Zoi.max(100),
age: Zoi.integer() |> Zoi.optional(),
email: Zoi.email()
})
@type t :: unquote(Zoi.type_spec(@schema))
end
Which will generate:
@type t :: %{
required(:name) => binary(),
optional(:age) => integer(),
required(:email) => binary()
}
Errors
When validation fails, Zoi returns a list of errors, each containing a message and the path to the invalid data. Even when errors are nested, Zoi will return all errors in a flattened list.
iex> schema = Zoi.map(%{name: Zoi.string(), age: Zoi.integer()})
iex> Zoi.parse(schema, %{name: 123, age: "thirty"})
{:error,
[
%Zoi.Error{
code: :invalid_type,
issue: {"invalid type: expected string", [type: :string]},
message: "invalid type: expected string",
path: [:name]
},
%Zoi.Error{
code: :invalid_type,
issue: {"invalid type: expected integer", [type: :integer]},
message: "invalid type: expected integer",
path: [:age]
}
]}
You can view the error in a map format using the Zoi.treefy_errors/1 function:
iex> schema = Zoi.map(%{name: Zoi.string(), age: Zoi.integer()})
iex> {:error, errors} = Zoi.parse(schema, %{name: 123, age: "thirty"})
iex> Zoi.treefy_errors(errors)
%{
name: ["invalid type: expected string"],
age: ["invalid type: expected integer"]
}
You can also customize error messages:
iex> schema = Zoi.string(error: "not a string")
iex> Zoi.parse(schema, :hi)
{:error,
[
%Zoi.Error{
code: :custom,
issue: {"not a string", [type: :string]},
message: "not a string",
path: []
}
]}
Phoenix forms
Zoi works seamlessly with Phoenix forms through the Phoenix.HTML.FormData protocol:
# Define schema inline
@user_schema Zoi.map(%{
name: Zoi.string() |> Zoi.min(3),
email: Zoi.email()
}) |> Zoi.Form.prepare()
# Parse and render (just like changesets!)
ctx = Zoi.Form.parse(@user_schema, params)
form = to_form(ctx, as: :user)
socket |> assign(:form, form)
# Use in your forms
~H"""
<.form for={@form} phx-submit="save">
<.input field={@form[:name]} label="Name" />
<.input field={@form[:email]} label="Email" />
<div>
<.button>Save</.button>
</div>
</.form>
"""
- See Rendering forms with Phoenix for a complete LiveView example.
- See Localizing errors with Gettext for translation support.
Metadata
Zoi supports 4 types of metadata:
description: Description of the schema.example: An example value that conforms to the schema.deprecated: Mark the schema as deprecated, it will emit a warning when parsing.metadata: A keyword list of arbitrary metadata.
You can use in all types, for example:
iex> schema = Zoi.string(description: "Hello", example: "World!", metadata: [identifier: "string"])
iex> Zoi.description(schema)
"Hello"
iex> Zoi.example(schema)
"World!"
iex> Zoi.metadata(schema)
[identifier: "string"]
description and example are also used when generating OpenAPI specs. See the Using Zoi to generate OpenAPI specs guide for more details.
JSON Schema
Zoi schemas can be converted to and from JSON Schema format:
iex> schema = Zoi.map(%{name: Zoi.string(), age: Zoi.integer()})
iex> Zoi.to_json_schema(schema)
%{
"$schema": "https://json-schema.org/draft/2020-12/schema",
type: :object,
properties: %{name: %{type: :string}, age: %{type: :integer}},
required: [:name, :age],
additionalProperties: false
}
You can also decode an existing JSON Schema into a Zoi schema using Zoi.from_json_schema/1. See Zoi.JSONSchema for the full type mapping.
Guides
Check the official guides for more examples and use cases:
- Quickstart Guide
- Recipes
- Main API Reference
- Using Zoi to generate OpenAPI specs
- Validating controller parameters
- Converting Keys From Object
- Generating Schemas from JSON
Acknowledgements
Zoi is inspired by different schema validation libraries, including:
探索相关项目
加载中…