Exdantic.RootSchema (exdantic v0.0.2)

View Source

RootSchema allows validation of non-dictionary types at the top level.

Similar to Pydantic's RootModel, this enables validation of values that are not maps/objects, such as arrays, primitives, or other structured data at the root level.

Examples

# Validate a list of integers
defmodule IntegerListSchema do
  use Exdantic.RootSchema, root: {:array, :integer}
end

{:ok, [1, 2, 3]} = IntegerListSchema.validate([1, 2, 3])

# Validate a single string with constraints
defmodule EmailSchema do
  use Exdantic.RootSchema,
    root: {:type, :string, [format: ~r/^[^ @]+@[^ @]+.[^ @]+$/]}
end

{:ok, "user@example.com"} = EmailSchema.validate("user@example.com")

# Validate a union type
defmodule StringOrNumberSchema do
  use Exdantic.RootSchema, root: {:union, [:string, :integer]}
end

{:ok, "hello"} = StringOrNumberSchema.validate("hello")
{:ok, 42} = StringOrNumberSchema.validate(42)

Summary

Functions

Configures a module to be a RootSchema for validating non-dictionary types.

Converts a root type definition to a JSON Schema.

Validates data against a root type definition.

Functions

__using__(opts)

(macro)
@spec __using__(keyword()) :: Macro.t()

Configures a module to be a RootSchema for validating non-dictionary types.

Options

  • :root - The type definition for the root value. This can be any valid Exdantic type definition including basic types, arrays, maps, unions, etc.

Examples

# Simple array validation
defmodule NumberListSchema do
  use Exdantic.RootSchema, root: {:array, :integer}
end

# Complex nested structure
defmodule NestedSchema do
  use Exdantic.RootSchema,
    root: {:array, {:map, {:string, {:union, [:string, :integer]}}}}
end

# Reference to another schema
defmodule UserListSchema do
  use Exdantic.RootSchema, root: {:array, UserSchema}
end

to_json_schema(root_type)

@spec to_json_schema(term()) :: map()

Converts a root type definition to a JSON Schema.

Parameters

  • root_type - The type definition to convert

Returns

  • A map representing the JSON Schema

validate_root(root_type, data)

@spec validate_root(term(), term()) ::
  {:ok, term()} | {:error, Exdantic.Error.t() | [Exdantic.Error.t()]}

Validates data against a root type definition.

This is the core validation function used by RootSchema modules.

Parameters

  • root_type - The type definition to validate against
  • data - The data to validate

Returns

  • {:ok, validated_data} on success
  • {:error, errors} on validation failures