View Source Peri (peri v0.1.0)

Peri is a schema validation library for Elixir, inspired by Clojure's Plumatic Schema. It focuses on validating raw maps and supports nested schemas and optional fields.

Usage

To define a schema, use the defschema macro. By default, all fields in the schema are optional unless specified as {:required, type}.

defmodule MySchemas do
  import Peri

  defschema :user, %{
    name: :string,
    age: :integer,
    email: {:required, :string},
    address: %{
      street: :string,
      city: :string
    }
  }
end

You can then use the schema to validate data:

user_data = %{name: "John", age: 30, email: "john@example.com", address: %{street: "123 Main St", city: "Somewhere"}}
case MySchemas.user(user_data) do
  {:ok, valid_data} -> IO.puts("Data is valid!")
  {:error, errors} -> IO.inspect(errors, label: "Validation errors")
end

Available Types

  • :string - Validates that the field is a binary (string).
  • :integer - Validates that the field is an integer.
  • :float - Validates that the field is a float.
  • :boolean - Validates that the field is a boolean.
  • {:required, type} - Marks the field as required and validates it according to the specified type.
  • :map - Validates that the field is a map without checking nested schema.

Summary

Functions

Defines a schema with a given name and schema definition.

Validates a given data map against a schema.

Functions

Link to this macro

defschema(name, schema)

View Source (macro)

Defines a schema with a given name and schema definition.

Examples

defmodule MySchemas do
  import Peri

  defschema :user, %{
    name: :string,
    age: :integer,
    email: {:required, :string}
  }
end

user_data = %{name: "John", age: 30, email: "john@example.com"}
MySchemas.user(user_data)
# => {:ok, %{name: "John", age: 30, email: "john@example.com"}}

invalid_data = %{name: "John", age: 30}
MySchemas.user(invalid_data)
# => {:error, [email: "is required"]}

Validates a given data map against a schema.

Returns {:ok, data} if the data is valid according to the schema, or {:error, errors} if there are validation errors.

Parameters

  • schema: The schema definition map.
  • data: The data map to be validated.

Examples

schema = %{
  name: :string,
  age: :integer,
  email: {:required, :string}
}

data = %{name: "John", age: 30, email: "john@example.com"}
Peri.validate(schema, data)
# => {:ok, %{name: "John", age: 30, email: "john@example.com"}}

invalid_data = %{name: "John", age: 30}
Peri.validate(schema, invalid_data)
# => {:error, [email: "is required"]}