Skip to content

Instantly share code, notes, and snippets.

@noelworden
Created May 22, 2020 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelworden/76aecc9153cb7dbaa00e1b227c08d455 to your computer and use it in GitHub Desktop.
Save noelworden/76aecc9153cb7dbaa00e1b227c08d455 to your computer and use it in GitHub Desktop.
defmodule Finance.SourceFiles.Data.Screen do
import Ecto.Changeset
def validate_decimal(changeset, fields) do
%{errors: errors} = changeset
fields_not_decimal =
for field <- fields,
not_decimal?(changeset, field),
do: field
case fields_not_decimal do
[] ->
changeset
_ ->
new_errors = Enum.map(fields_not_decimal, &{&1, {"must be a number", []}})
%{changeset | errors: new_errors ++ errors, valid?: false}
end
end
def validate_decimal_less_than_equal_zero(changeset, field) do
value = get_field(changeset, field)
with {:nil_check, true} <- {:nil_check, value != nil},
{:ok, decimal} <- Decimal.parse(value),
cmp when cmp in [:lt, :eq] <- Decimal.cmp(decimal, 0) do
changeset
else
{:nil_check, false} -> changeset
:error -> add_error(changeset, field, "must be a number")
:gt -> add_error(changeset, field, "must be less than or equal to zero")
end
end
defp not_decimal?(changeset, field) do
value = get_field(changeset, field)
if value == nil || Decimal.parse(value) != :error do
false
else
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment