PhoenixKitWeb.Components.Core.DecimalInput (phoenix_kit v2.26.0)

Copy Markdown View Source

A form control for numbers a person types — quantities, prices, weights, lengths — where a comma and a dot must both work and nothing may be rounded.

Why not <.input type="number">: the browser owns a number control. Its decimal separator follows the page/element locale, so on a page with lang="et" a typed 2.5 can be swallowed (the field submits ""), and on lang="en" a typed 2,5 is; step makes any other precision invalid and silently blocks a phx-submit; the spinner arrows steal wheel and arrow-key events. This component renders a plain <input type="text" inputmode="decimal">: the mobile keyboard still opens on digits, and the server decides what the text means with PhoenixKit.Utils.Number.parse_decimal/2 — comma or dot, grouping spaces, sign, and nothing else.

Otherwise it is <.input>: a Phoenix.HTML.FormField or raw name/value, label, gettext-translated errors, class on the control and wrapper_class on the phx-feedback-for wrapper, the required marker, and daisyUI 5 styling.

Summary

Functions

Renders a free-decimal text control.

Functions

decimal_input(assigns)

Renders a free-decimal text control.

The value is shown normalized when it is a number (Decimal.new("2.500") → 2.5, 1E+3 → 1000) and echoed back unchanged when it is a binary, so the text a person typed survives a re-render exactly as typed — a 2,5 does not turn into 2.5 under their cursor.

Examples

<%!-- FormField binding: name, id, value, errors derived --%>
<.decimal_input field={@form[:quantity]} label="Quantity" />

<%!-- Unit suffix inside the field --%>
<.decimal_input field={@form[:weight]} label="Weight" unit="kg" />

<%!-- Raw name/value for a row in a list, small and right-aligned --%>
<.decimal_input
  id={"row-#{row.id}-qty"}
  name="qty"
  value={row.qty}
  class="input-sm text-right"
  phx-debounce="400"
  phx-blur="commit_qty"
  phx-value-row_id={row.id}
/>

Parse the submitted text with PhoenixKit.Utils.Number.parse_decimal/2:

case Number.parse_decimal(params["qty"], min: 0) do
  {:ok, qty} -> ...
  {:error, :empty} -> ...
  {:error, _reason} -> ...
end

Attributes

  • id (:any) - Defaults to nil.
  • name (:any)
  • label (:string) - Defaults to nil.
  • value (:any) - Defaults to nil.
  • unit (:string) - a unit suffix rendered inside the field, after the number (kg, m, pcs). Defaults to nil.
  • class (:any) - extra classes merged onto the control — daisyUI modifiers like input-sm, input-primary, or text-right. Defaults to nil.
  • wrapper_class (:any) - extra classes for the outer <div phx-feedback-for> wrapper. Defaults to nil.
  • field (Phoenix.HTML.FormField) - a form field struct retrieved from the form, for example: @form[:quantity].
  • errors (:list) - Defaults to [].
  • Global attributes are accepted. Supports all globals plus: ["autofocus", "disabled", "form", "maxlength", "placeholder", "readonly", "required", "size"].