I’m using the Decimal package to work with a field in my changeset.
field :amount, :decimal
I can validate it with
validate_number so that it should be greater or equal to a given number.
But for now I would like the user to submit an integer for this field (:amount).
I do not want to change the Ecto type to
:integer but just want to have a decimal number with zero as decimal part.
Please any suggestion on how to achieve this with a custom Ecto validator, given that the field is of type
Maybe you can check if it equals to the rounded version of itself.
defp validate_integer(changeset, field) do
if integer?(get_field(changeset, field)) do
add_error(changeset, field, "An integer is expected.")
defp integer?(decimal) do
Thank you @Aetherus!
it works fine. I just had to add one more clause to the
defp integer?(nil), do: false
Decimal.round/1 function throws an exception when rendering a new empty form.
I was assuming that the field should not be
nil and is validated with
Ecto.Changeset.validate_required before piping into this
validate_integer. My fault.
Yes i used
validate_required before piping into the integer validator. I think even with that, we need to check if the field is nil. Anyway thanks again. ^^
Ecto.Changeset.validate_change would give you the "don’t bother doing this if the value is
nil" behavior as well.