Axn.Steps.CastValidateParams (Axn v0.2.0)
View SourceBuilt-in step for casting and validating parameters with schema validation and optional custom validation.
This step takes raw parameters from the context, casts them according to a schema, and optionally applies custom validation logic.
Summary
Functions
Casts and validates parameters according to a schema with optional custom validation.
Types
@type validate_fun() :: (Ecto.Changeset.t(), Axn.Context.t() -> Ecto.Changeset.t())
Functions
@spec cast_validate_params( Axn.Context.t(), keyword() ) :: {:cont, Axn.Context.t()} | {:halt, {:error, map()}}
Casts and validates parameters according to a schema with optional custom validation.
This step takes raw parameters from the context, casts them according to a schema,
and optionally applies custom validation logic. The schema uses the Params library
format and supports required fields, optional fields, defaults, and custom validation.
Options
:schema- Parameter schema map (required). UsesParams.Schemaformat.:validate- Custom validation function that receives changeset (optional).
Schema Format
The schema follows the Params.Schema format:
field!: :type- Required field of the specified typefield: :type- Optional field of the specified typefield: [field: :type, default: value]- Field with default valuefield: [field: :type, cast: &func/1]- Field with custom cast function
Supported types include :string, :integer, :boolean, :atom, :map, :list, etc.
Custom Validation
The optional :validate function receives an Ecto.Changeset and the current Axn.Context
after initial casting and validation. It should return a modified changeset with any
additional validations applied:
def validate_params(changeset, ctx) do
changeset
|> validate_format(:email, ~r/@/)
|> validate_length(:name, min: 2)
|> validate_user_permissions(ctx.assigns.current_user)
endContext Updates
On success, this step updates the context:
ctx.params- Contains the cast and validated parametersctx.private.raw_params- Contains the original raw parametersctx.private.changeset- Contains the final changeset
Examples
# Basic schema validation
step :cast_validate_params, schema: %{
email!: :string,
name: :string,
age: [field: :integer, default: 18]
}
# With custom validation
step :cast_validate_params,
schema: %{phone!: :string, region: [field: :string, default: "US"]},
validate: &__MODULE__.validate_phone_number/2
def validate_phone_number(changeset, ctx) do
params = Params.to_map(changeset)
validate_format(changeset, :phone, phone_regex_for_region(params.region))
endReturns
{:cont, updated_context}- Parameters are valid, pipeline continues{:halt, {:error, %{reason: :invalid_params, changeset: changeset}}}- Validation failed
The error changeset contains all validation errors and can be used to generate user-friendly error messages.