Kurisu
How to validate that a decimal number is an integer in an Ecto changeset?
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 :decimal?
Marked As Solved
Aetherus
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
changeset
else
add_error(changeset, field, "An integer is expected.")
end
end
defp integer?(decimal) do
decimal
|> Decimal.round()
|> Decimal.equal?(decimal)
end
Also Liked
Kurisu
Aetherus
My pleasure.
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.
al2o3cr
FWIW, Ecto.Changeset.validate_change would give you the “don’t bother doing this if the value is nil” behavior as well.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









