GuardedStruct.Derive.Extension

Copy Markdown View Source

derives

Container for custom validator and sanitizer ops.

Example

defmodule MyApp.Derives do use GuardedStruct.Derive.Extension

derives do validator :slug, fn input -> is_binary(input) and Regex.match?(~r/^[a-z0-9-]+$/, input) end

sanitizer :slugify, fn input when is_binary(input) -> input |> String.downcase() |> String.replace(~r/[^a-z0-9-]+/u, "-") end end end

Nested DSLs

derives.validator

validator name, fun

Declare a custom validator op callable as validate(<name>) from any GuardedStruct module that has this extension wired in.

Arguments

NameTypeDefaultDocs
nameatomOp name. Used as validate(<name>) in derive strings.
funanySingle-arg function. Return value semantics: true — input passes false — input fails (default error message) {:error, field, action, message} — explicit error any other value — used as the validated (coerced) output

derives.sanitizer

sanitizer name, fun

Declare a custom sanitizer op callable as sanitize(<name>). Runs before validation in the derive pipeline; the return value replaces the input.

Arguments

NameTypeDefaultDocs
nameatomOp name. Used as sanitize(<name>) in derive strings.
funanySingle-arg function. Return value replaces the input.