Valpa.Custom (Valpa v0.1.2)

View Source

“Custom” validators that wrap user-provided functions or modules implementing the Valpa.CustomValidator behaviour and always return

  • {:ok, value}
  • {:ok, map}
  • {:error, reason}

instead of raising. All functions accept:

  • A raw value
  • An {:ok, value} tuple (it unwraps and re-validates)
  • An {:error, reason} tuple (it propagates unchanged)

This makes them fully composable in |> pipelines.

Summary

Functions

Like validate/2 but treats nil as valid and returns {:ok, nil}.

Like validator/2 but returns {:ok, nil} if the input is nil.

Like validator/3 but returns {:ok, map} if Map.fetch!(map, key) is nil.

Apply a simple validation function to input.

Run a Valpa.CustomValidator against a single map field.

Functions

maybe_validate(input, validate)

@spec maybe_validate(
  term() | {:ok, term()} | {:error, any()},
  Valpa.CustomValidator.validate()
) :: {:ok, term() | nil} | {:error, any()}

Like validate/2 but treats nil as valid and returns {:ok, nil}.

maybe_validator(input, validator)

@spec maybe_validator(
  term() | {:ok, term()} | {:error, any()},
  Valpa.CustomValidator.t()
) :: {:ok, term() | nil} | {:error, any()}

Like validator/2 but returns {:ok, nil} if the input is nil.

maybe_validator(input, key, validator)

@spec maybe_validator(
  map() | {:ok, map()} | {:error, any()},
  atom(),
  Valpa.CustomValidator.t()
) :: {:ok, map()} | {:error, any()}

Like validator/3 but returns {:ok, map} if Map.fetch!(map, key) is nil.

validate(input, validate)

@spec validate(
  term() | {:ok, term()} | {:error, any()},
  Valpa.CustomValidator.validate()
) :: {:ok, term()} | {:error, any()}

Apply a simple validation function to input.

Parameters

  • input — raw term, {:ok, term}, or {:error, reason}
  • validate — a (term -> :ok | {:error, reason}) function

Returns

  • {:ok, value} if validate.(value) == :ok
  • {:error, reason} if validate.(value) == {:error, reason}
  • Propagates existing {:error, reason} unchanged

validator(input, validator)

@spec validator(
  term() | {:ok, term()} | {:error, any()},
  Valpa.CustomValidator.t()
) :: {:ok, term()} | {:error, any()}

Delegate to a Valpa.CustomValidator module.

Parameters

  • input — raw term, {:ok, term}, or {:error, reason}
  • validator — a module implementing Valpa.CustomValidator

Returns

  • {:ok, value} on success
  • {:error, reason} on failure
  • Propagates existing {:error, reason} unchanged

validator(input, key, validator)

@spec validator(
  map() | {:ok, map()} | {:error, any()},
  atom(),
  Valpa.CustomValidator.t()
) :: {:ok, map()} | {:error, any()}

Run a Valpa.CustomValidator against a single map field.

Returns

  • {:ok, map} if the field passes validation
  • {:error, reason} on failure
  • Propagates existing {:error, reason} unchanged