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 aretrue
andfalse
. The default isfalse
.:required
- Setting:required
totrue
will cause a validation error when a field is not present or the value isnil
. Allowed values for required aretrue
andfalse
. The default isfalse
.
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}}