Skip to content

Instantly share code, notes, and snippets.

@teamon
Created September 6, 2016 15:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamon/acf0c2d277bb2489fff9050ca174ce6f to your computer and use it in GitHub Desktop.
Save teamon/acf0c2d277bb2489fff9050ca174ce6f to your computer and use it in GitHub Desktop.
@doc """
Validate each array element with validator
Examples
iex> changeset
...> |> validate_each(:emails, &validate_email)
...> |> validate_each(:phones, &validate_format(&1, &2, ~r/\d+/))
...> |> validate_each(:phones, &validate_length/3, is: 4)
"""
def validate_each(changeset, field, validator, opts) do
validate_each(changeset, field, & apply(validator, [&1,&2,opts]))
end
def validate_each(changeset, field, validator) do
%{changes: changes, errors: errors} = changeset
new = case Map.get(changes, field) do
nil -> []
values -> Enum.flat_map values, fn value ->
# since validators work only on single fields we need to trick them
single_changeset = %Ecto.Changeset{changes: %{field => value}, errors: []}
validator.(single_changeset, field).errors
end
end
case new do
[] -> changeset
[_|_] -> %{changeset | errors: new ++ errors, valid?: false}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment