defmodule ExWeb.Validation do def put_error(%{errors: errors} = change, attribute, error) do errors = Map.new(errors) errors = Map.put(errors, attribute, error) %{change|errors: Map.to_list(errors)} end def exists(%{attributes: attributes} = change, attribute) do case Map.fetch(attributes, attribute) do {:ok, value} -> case value do nil -> put_error(change, attribute, "required") "" -> put_error(change, attribute, "required") _ -> change end _ -> put_error(change, attribute, "required") end end def reject_if_empty(change, []), do: change def reject_if_empty(%{attributes: attributes} = change, [attr|check_attributes]) do case Map.fetch(attributes, attr) do {:ok, nil} -> reject_if_empty(%{change | attributes: Map.delete(attributes, attr)}, check_attributes) _ -> reject_if_empty(%{change | attributes: attributes}, check_attributes) end end def reject_if_empty(change, attr), do: reject_if_empty(change, [attr]) def format(%{attributes: attributes} = change, attribute, regex) do case Map.fetch(attributes, attribute) do {:ok, nil} -> change {:ok, value} -> if String.match?(value, regex) do change else put_error(change, attribute, "invalid format") end _ -> change end end def cast(%{attributes: attributes} = change, cast_attributes) do attrs = cast_attributes |> Enum.map(fn k -> {k, cast_value(Map.get(attributes, k) || Map.get(attributes, "#{k}"))} end) %{change | attributes: Map.new(attrs)} end defp cast_value("") do nil end defp cast_value(nil) do nil end defp cast_value(val) do val end end