Validating a money value on the front end that gets converted to an int for the database

Not sure where this lands.

I have a very specific problem that I’m not even sure how to ask the correct questions for.

I have a schema defined that has a price stored as an integer, cents.

field :price, :integer, default: 0

With the form helpers, Phoenix correctly recognizes this value as a integer.

Validation kicks up an error if I pass a decimal value to the field.

errors: [price: {"is invalid", [type: :integer, validation: :cast]}]

This is also correct behavior.

However, I anticipate this user interpretation of this field (money can involve decimals) when I accept the parameters and catch cases appropriately to convert the value to cents for storage in the database. I also change it back to a money format when I populate the form.

I can submit the form with the “invalid type” error for some reason. I’m not bothered. I’m just wondering how to either:

  1. Ignore the type for validation since I’m catching it on my own, or
  2. accept either float or integer types for the purposes of validation – on the changeset, perhaps?

Like I said, I don’t know the correct questions to ask to search for a solution, if it exists at all. Any guidance is appreciated.

Have a look at the Ecto.Type behaviour. The examples in the docs should give you a good idea of how you can possibly make it work.

That’s exactly what I need. Money Type, ho!

Edit: 10 minutes to implement! I am going on three hours of sleep! I am SO HAPPY! THANK YOU.