GuardedStruct.Validate (GuardedStruct v0.1.0-beta.1)

Copy Markdown View Source

Standalone validators that reuse a GuardedStruct schema without going through the full builder/1 pipeline.

Three tiers:

  • run/2 — derive op-string against a single value, no module needed.
  • field/3,4 — validate one named field of a guardedstruct module. Cross-field dependencies (on:, domain:) honoured by mode.
  • partial/2 — validate a subset of fields together. Missing fields skipped (no enforce_keys check). Useful for form-as-you-type and PATCH-style endpoints.

Returns the validated value (or partial map) on success, an error list with the same shape as builder/1 on failure.

Summary

Functions

Validate a single named field of a guardedstruct module.

Validate a partial map of fields. Missing fields are skipped (no enforce_keys check). Cross-field deps resolve from the same input.

Validate a value against a derive op-string. No module needed.

Types

error()

@type error() :: %{
  :field => atom(),
  :action => atom(),
  :message => String.t(),
  optional(any()) => any()
}

Functions

field(module, field_name, value, opts \\ [])

@spec field(module(), atom(), any(), keyword()) :: {:ok, any()} | {:error, [error()]}

Validate a single named field of a guardedstruct module.

Modes

  • :strict (default) — honour on: and domain: core keys. Errors if a cross-field dependency can't be resolved.
  • :isolated — skip cross-field deps. Run only derive: + validator:.

Context

Pass context: %{other_field: ...} to provide values for cross-field dependency resolution.

partial(module, attrs)

@spec partial(module(), map()) :: {:ok, map()} | {:error, [error()]}

Validate a partial map of fields. Missing fields are skipped (no enforce_keys check). Cross-field deps resolve from the same input.

run(derive_string, value)

@spec run(String.t(), any()) :: {:ok, any()} | {:error, [error()]}

Validate a value against a derive op-string. No module needed.

iex> GuardedStruct.Validate.run("validate(string, max_len=80)", "hi")
{:ok, "hi"}