litmus v1.0.1 Litmus.Type.Number View Source

This type validates that values are numbers, and converts them to numbers if possible. It converts "stringified" numerical values to numbers.

Options

  • :default - Setting :default will populate a field with the provided value, assuming that it is not present already. If a field already has a value present, it will not be altered.

  • :min - Specifies the minimum value of the field.

  • :max - Specifies the maximum value of the field.

  • :integer - Specifies that the number must be an integer (no floating point). Allowed values are true and false. The default is false.

  • :required - Setting :required to true will cause a validation error when a field is not present or the value is nil. Allowed values for required are true and false. The default is false.

Examples

iex> schema = %{
...>   "id" => %Litmus.Type.Number{
...>     integer: true
...>   },
...>   "gpa" => %Litmus.Type.Number{
...>     min: 0,
...>     max: 4
...>   }
...> }
iex> params = %{"id" => "123", "gpa" => 3.8}
iex> Litmus.validate(params, schema)
{:ok, %{"id" => 123, "gpa" => 3.8}}
iex> params = %{"id" => "123.456", "gpa" => 3.8}
iex> Litmus.validate(params, schema)
{:error, "id must be an integer"}

iex> schema = %{
...>   "gpa" => %Litmus.Type.Number{
...>     default: 4
...>   }
...> }
iex> Litmus.validate(%{}, schema)
{:ok, %{"gpa" => 4}}

Link to this section Summary

Link to this section Types

Specs

t() :: %Litmus.Type.Number{
  default: any(),
  integer: boolean(),
  max: number() | nil,
  min: number() | nil,
  required: boolean()
}

Link to this section Functions

Link to this function

validate_field(type, field, data)

View Source

Specs

validate_field(t(), term(), map()) :: {:ok, map()} | {:error, String.t()}