Helpers for validating and normalizing Elixir data structures.
The validation works as simple composable functions, allowing simple validations...
iex> validator = integer(max: 2)
iex> validator.(2)
{:ok, 2}
iex> validator.(4)
{:error, "is greater than 2"}
...data casting...
iex> validator = map_of(%{name: string(required: true), age: integer(min: 1)})
iex> validator.(%{"name" => "Jhon", "age": "26"})
{:ok, %{name: "Jhon", age: 26}}
iex> validator.(%{"age": "a"})
{:error, %{name: "is blank", age: "is not a number"}}
...and more complex use cases:
iex> address = map_of(%{
...> city: string(required: true),
...> state: string(required: true, min: 2, max: 2)
...> })
iex> person = map_of(%{
...> name: string(required: true),
...> age: integer(min: 1),
...> addresses: list_of(address)
...> })
iex> validator = list_of(person)
iex> data = [
...> %{
...> "name" => "Jhon",
...> "age" => "aa",
...> "addresses" => [
...> %{"city" => "New York", "state" => "NY"},
...> %{"city" => "Los Angeles", "state" => "LA"},
...> ]
...> },
...> %{
...> "name" => "Alex",
...> "addresses" => [
...> %{"city" => "Chicago", "states" => "IL"},
...> %{"city" => "San Francisco", "state" => "CA"},
...> ]
...> }
...> ]
iex> validator.(data)
{:error, %{
0 => %{age: "is not a number"},
1 => %{addresses: %{0 => %{state: "is blank"}}}
}}
The package can be installed by adding ex_validator
to your list of dependencies in mix.exs
:
def deps do
[
{:ex_validator, "~> 0.1.0"}
]
end
Online documentation is available here.
The ExValidator source code is lecensed under the MIT License