Created
September 6, 2016 15:11
-
-
Save teamon/acf0c2d277bb2489fff9050ca174ce6f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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