Money. Input. Changeset
(Money.Input v0.1.0)
View Source
Ecto.Changeset helpers for Money.Input.
Only compiled when :ecto is loaded. Two functions, applied
in order:
cast_money/3— converts a%{"amount" => ..., "currency" => ...}form submission into aMoney.t/0change. WrapsMoney.Input.Cast.cast/2.validate_money/3— applies business rules (bounds, precision, currency match) to the cast value. WrapsMoney.Input.Validator.validate_money/2.
Plain-number fields (:integer, :decimal) are validated
by the sibling Localize.Inputs.Changeset.validate_number/3.
schema "products" do
field :price, Money.Ecto.Composite.Type
end
def changeset(product, attrs) do
product
|> Ecto.Changeset.cast(attrs, [:price])
|> Money.Input.Changeset.validate_money(:price,
min: Money.new(:USD, "0.01"),
max: Money.new(:USD, 9999))
end
Summary
Functions
Casts a nested %{"amount" => ..., "currency" => ...} form
submission into a Money.t/0 and puts it on the changeset.
Validates a Money.t/0 field with the rules from
Money.Input.Validator.validate_money/2.
Functions
@spec cast_money(Ecto.Changeset.t(), atom(), Keyword.t()) :: Ecto.Changeset.t()
Casts a nested %{"amount" => ..., "currency" => ...} form
submission into a Money.t/0 and puts it on the changeset.
Use this when the field is not typed as
Money.Ecto.Composite.Type (which casts the same map shape
automatically). Delegates to Money.Input.Cast.cast/2, which
is locale-aware via Money.new/3, so casting works even in
the Path A fallback when the AutoNumeric JS hook isn't loaded.
Arguments
changesetis anEcto.Changeset.fieldis the field name.optionsis a keyword list.
Options
:locale— locale to parse the amount under. Defaults toLocalize.get_locale/0.:currency— fallback currency if the submitted map omits thecurrencykey.
Returns
- The changeset with a
Money.t/0change put onfield, or with an error added if the amount/currency can't be parsed.
@spec validate_money(Ecto.Changeset.t(), atom(), Keyword.t()) :: Ecto.Changeset.t()
Validates a Money.t/0 field with the rules from
Money.Input.Validator.validate_money/2.
Arguments
changesetis anEcto.Changeset.fieldis the field name.optionsis a keyword list forwarded to the validator (:min,:max,:required,:currency).
Returns
- The changeset, with any errors added.