pushex v0.1.2 Pushex.Validators.Type

Ensure the value has the correct type.

The type can be provided in the following form:

  • type: An atom representing the type. It can be any of the TYPE in Elixir is_TYPE functions. :any is treated as a special case and accepts any type.
  • [type]: A list of types as described above. When a list is passed, the value will be valid if it any of the types in the list.
  • type: inner_type: Type should be either map, list, tuple, or function. The usage are as follow

    • function: arity: checks if the function has the correct arity.
    • map: {key_type, value_type}: checks keys and value in the map with the provided types.
    • list: type: checks every element in the list for the given types.
    • tuple: {type_a, type_b}: check each element of the tuple with the provided types, the types tuple should be the same size as the tuple itself.

Options

  • :is: Required. The type of the value, in the format described above.
  • :message: Optional. A custom error message. May be in EEx format and use the fields described in “Custom Error Messages,” below.

Examples

iex> Vex.Validators.Type.validate(1, is: :binary)
{:error, "must be of type :binary"}
iex> Vex.Validators.Type.validate(1, is: :number)
:ok
iex> Vex.Validators.Type.validate(nil, is: nil)
:ok
iex> Vex.Validators.Type.validate(1, is: :integer)
:ok
iex> Vex.Validators.Type.validate("foo"", is: :binary)
:ok
iex> Vex.Validators.Type.validate([1, 2, 3], is: [list: :integer])
:ok
iex> Vex.Validators.Type.validate(%{:a => 1, "b" => 2, 3 => 4}, is: :map)
:ok
iex> Vex.Validators.Type.validate(%{:a => 1, "b" => 2}, is: [map: {[:binary, :atom], :any}])
:ok
iex> Vex.Validators.Type.validate(%{"b" => 2, 3 => 4}, is: [map: {[:binary, :atom], :any}])
{:error, "must be of type {:map, {[:binary, :atom], :any}}"}

Custom Error Messages

Custom error messages (in EEx format), provided as :message, can use the following values:

iex> Vex.Validators.Type.__validator__(:message_fields)
[value: "The bad value"]

An example:

iex> Vex.Validators.Type.validate([1], is: :binary, message: "<%= inspect value %> is not a string")
{:error, "[1] is not a string"}

Summary

Functions

Validates the value against the given type. See the module documentation for more info

Functions

validate(value, options)
validate(any, Keyword.t) :: :ok | {:error, String.t}

Validates the value against the given type. See the module documentation for more info.

validate(data, context, options)

Callback implementation for Vex.Validator.Behaviour.validate/3.