Introducing a new way to review your PRs.

Read the announcement

petalframework / petal_components

Phoenix + Live View HEEX Components

View on GitHub

24 documents · Updated Sep 2, 2026

docs / form-controls

Form controls and validation

Petal Components provides reusable Phoenix function components for collecting application data. The components share a form-field model so values can come from Phoenix form fields, user input can return through normal form events, and validation feedback can appear beside the control that needs attention.

Component model

Field wrappers

The field component is the main high-level control. It combines a label, a control, help text, and validation errors in one wrapper. It can derive the control name, id, value, label, and errors from a %Phoenix.HTML.FormField{} such as @form[:email], or it can accept those values directly for a control outside a Phoenix form. The component selects the control family through type, including text, date, numeric, select, checkbox, radio, switch, combobox, and range forms. lib/petal_components/field.ex defines this shared contract.

The wrapper separates presentation from the value contract. A required field marks the label and passes the native constraint to the control. An errors list marks the wrapper and renders one or more messages. Help text remains optional. For compound controls such as checkbox groups, radio groups, radio cards, and dual ranges, the wrapper labels the group and reports its related errors as one field.

References: lib/…/field.ex• L5-161 lib/…/field.ex• L163-192 lib/…/field.ex• L871-934

Pure controls

The input component supplies the control without a label or error wrapper. Use it when the surrounding layout owns the label or when a control is part of another component, such as an input_group. It accepts a Phoenix form field or explicit name, id, and value data and passes common HTML constraints such as required, min, max, pattern, and disabled to the real control. A bare file input may omit value because the browser owns the selected file value.

This split lets one value source serve different layouts. Use field for a complete form row. Use input when the control must compose with custom content. The text and structured inputs page covers the text, date, range, OTP, and combobox families in more detail.

References: lib/…/input.ex• L5-44 lib/…/input.ex• L84-109 lib/…/input.ex• L111-123

Legacy form helpers

The PetalComponents.Form module is the older form API. Its form_field component still combines a Phoenix form and field atom with a label, control type, help text, and error output, while its lower-level helpers wrap Phoenix HTML form functions. New work should use field and input, which use %Phoenix.HTML.FormField{} directly. Existing applications can keep the legacy helpers while moving individual fields to the newer API.

References: lib/…/form.ex• L1-15 lib/…/form.ex• L71-134 lib/…/form.ex• L298-304

Phoenix form lifecycle

Form value lifecycle

Phoenix owns the form value and validation cycle. A changeset becomes a Phoenix form, a component reads one field from that form, and the browser posts the control's name and value back through submit or phx-change. The server then builds the next form state, which the component renders again.

The field components use Phoenix field names and values rather than a separate client data store. This keeps changeset casting, server validation, form recovery, and re-rendered values in the same path as native controls.

The following flow shows the normal relationship between server validation and the reusable control layer.

flowchart LR
    A[Changeset] --> B[Phoenix form]
    B --> C[Field or input component]
    C --> D[Native or enhanced form control]
    D -->|submit or phx-change| E[Form params]
    E --> F[Changeset validation]
    F --> B
    B -->|used field errors| C

References: lib/…/field.ex• L163-177 lib/…/input.ex• L92-101 lib/…/form.ex• L881-885

Validation states

Validation has two layers. Native browser rules provide immediate checks for attributes such as required, min, max, maxlength, and pattern. Changesets provide the application rules and return errors through the Phoenix form. The components render both layers without replacing server validation. The numeric spinbutton is an exception for bounds because it uses a text input; its min and max behavior comes from the control and must also be checked by the server.

Field errors follow Phoenix's used-input behavior. An error on a field that the user has not touched is not shown by the field wrapper. Once the field has submitted or changed, its translated errors become visible. Callers can also pass an explicit error list when the value does not come from a Phoenix form field.

Error text can use the configured :error_translator_function. Without one, the field layer replaces common interpolation values and falls back to a plain invalid-value message when it cannot render an error value safely.

References: lib/…/field.ex• L163-176 lib/…/field.ex• L948-1014 lib/…/form.ex• L723-735 lib/…/form.ex• L750-789

Control families

Text and structured inputs

Text controls preserve native browser input behavior while adding shared visual states. The family includes text-like inputs, textareas, date and time inputs, color and file inputs, single and dual range controls, password visibility, copy actions, and clear actions. These controls still post ordinary named values, so a parent Phoenix form does not need a special value protocol.

The OTP control presents a segmented code entry surface while keeping one real text input as the form value. It limits the accepted characters, supports numeric or alphanumeric entry, enables one-time-code autofill, and emits petal:otp-complete when all positions contain a value. Its painted slots are presentation only, so paste and form submission use the same input value.

The combo-box control adds search and choice behavior to a native form value. Its visible input or trigger supports the combobox and listbox interaction pattern, while a hidden native select remains the submitted value. Single selection posts one value. Multiple selection posts a list under a name ending in []. Remote search and free-text creation extend the option source, but the selected value still returns through the form control.

See Text and structured inputs for the value rules, options, client behavior, and detailed states of these controls.

References: lib/…/input.ex• L111-275 lib/…/input.ex• L277-388 lib/…/input_otp.ex• L4-16 lib/…/combo_box.ex• L3-25 lib/…/combo_box.ex• L290-326

Numeric inputs

The numeric field provides a quantity control for values such as counts, prices, and percentages. It uses one text input with spinbutton semantics so it can keep partial user input readable while its buttons, keys, and wheel apply steps. Bounds, step size, larger steps, and display precision shape the interaction, while the submitted value remains form data.

The field wrapper resolves one id for the label and the browser hook. Its stacked, split, and plain variants change the controls around the input rather than the value contract. Use the wrapper when the control needs help text and changeset errors. A standalone numeric field needs its own accessible name. See Advanced form inputs and uploads for related advanced input behavior.

References: lib/…/field.ex• L350-390 lib/…/number_field.ex• L1-25 lib/…/number_field.ex• L130-219

File inputs

File inputs keep the browser's native file-selection behavior. The shared field wrapper supplies the label, help text, and validation area, while the pure input form fits a file picker into a layout that owns those pieces. The component does not require a prefilled value because a selected file is supplied by the browser during form interaction.

Use Advanced form inputs and uploads for the upload-specific flow. The form control layer only defines how the file picker is named, labelled, styled, and included in the surrounding validation model.

References: lib/…/field.ex• L194-207 lib/…/field.ex• L899-918 lib/…/input.ex• L92-109 lib/…/input.ex• L378-388

Selection controls

Selection controls express a choice rather than free text. Checkbox groups submit several values, radio groups and radio cards submit one value, and switches submit a boolean-style value with a false fallback when unchecked. The field wrapper gives these compound controls one label and one error area.

The toggle group is a server-driven choice rail. In single mode it uses native radio semantics and keeps one selected value. In multiple mode it uses buttons with aria-pressed and treats the value as a list. A press sends the option in phx-value-toggle; the LiveView assigns the new value back, so the server remains the source of truth.

The rating control has a display mode and an interactive mode. Display mode shows a score with stars, hearts, faces, or a custom glyph. Interactive mode renders a labelled radio group that posts its value in a named form field. Whole and half precision change the available values, while face ratings remain a five-point whole-number scale.

See Selection controls for the detailed choice, preference, and rating behavior.

References: lib/…/field.ex• L449-637 lib/…/toggle_group.ex• L6-21 lib/…/toggle_group.ex• L108-165 lib/…/rating.ex• L3-14 lib/…/rating.ex• L87-188

Accessibility contracts

Labels and descriptions

A complete field keeps the label next to the control and connects it to the focusable element when one exists. The field wrapper uses the form field id for ordinary controls. A combobox points the label at its visible input or trigger rather than at its roleless wrapper. Compound controls use a group label because one label cannot describe each member as a separate field.

Help text and errors are separate pieces of content. The field layer makes them visible in the field flow. The combo box also exposes its required error region to the visible combobox because its native select is hidden from the accessibility tree. Standalone controls must receive their own accessible name, such as the label on a combo box, the aria_label on a toggle group, the label on an interactive rating, or an accessible label on a numeric field.

References: lib/…/field.ex• L228-250 lib/…/field.ex• L304-331 lib/…/field.ex• L896-907 lib/…/combo_box.ex• L158-182 lib/…/combo_box.ex• L328-360 lib/…/number_field.ex• L66-77

Native semantics

The controls prefer native HTML semantics where those semantics match the user task. Checkboxes, radios, selects, range inputs, and interactive ratings remain form controls. Single toggle groups expose a radiogroup. Multiple toggle groups expose a group of pressed buttons. A combo box uses the WAI-ARIA combobox and listbox pattern for its visible surface, while its native select preserves form behavior. Numeric fields use spinbutton semantics on their real text input.

Disabled state reaches the real control and its related actions. Required state reaches the browser constraint layer and the visible accessible control where an enhanced surface hides the native one. The OTP slots are aria-hidden because the single real input owns focus, value entry, and autofill.

References: lib/…/toggle_group.ex• L135-165 lib/…/rating.ex• L110-187 lib/…/input_otp.ex• L47-77 lib/…/combo_box.ex• L290-326 lib/…/combo_box.ex• L377-495 lib/…/number_field.ex• L250-264

Client-assisted states

Some controls use the JavaScript bundle only to improve a native control's surface. Password visibility changes the input type and its button state. Copy and clear actions update feedback or dispatch an input event. Range hooks update the visual fill. The OTP hook mirrors one input into painted slots. The combo-box hook filters options, manages the panel, and keeps its visible surface aligned with the native select. The numeric hook applies steps and display updates to the spinbutton.

These enhancements do not define a second form model. The real input or select remains the value source. LiveView patches can therefore restore server values, while the hook preserves short-lived display state such as an open panel or a typed search query. The numeric field and filled range also render their initial visual state on the server, so the first view remains useful before the browser hook mounts.

References: lib/…/input.ex• L358-375 lib/…/number_field.ex• L198-293 assets/…/petal_components.js• L255-357 assets/…/petal_components.js• L372-399 assets/…/petal_components.js• L1369-1436 assets/…/petal_components.js• L3880-3957 assets/…/petal_components.js• L4160-4197

Form field composition

Shared input surfaces

The input_group component places an input and optional addons on one visual surface. Leading and trailing slots hold prefixes, suffixes, icons, buttons, or keyboard hints. Block slots place full-width content above or below the input, which suits toolbars and character counts. The group owns the shared border and focus treatment, so a pure input can fit inside without changing its value contract.

Composition works best when each concern has one owner. Let field own the label, help, and errors. Let input_group own the shared surface. Put input or another control in the inner slot. For controls with their own panel or multiple focus targets, keep their required accessible name on the actual control rather than on a decorative wrapper.

References: lib/…/input_group.ex• L4-15 lib/…/input_group.ex• L35-69 lib/…/field.ex• L335-351

Public component access

use PetalComponents imports the form-related components into a Phoenix component module. This includes Field, Form, Input, InputGroup, InputOtp, ComboBox, ToggleGroup, and Rating. The JavaScript bundle is a separate browser boundary for controls that need client behavior, so an application that uses those enhanced states must register the exported hooks with its LiveSocket.

References: lib/petal_components.ex• L19-77 assets/…/petal_components.js• L5620-5643

Change checklist

When these files or sections are changed, remember to consider these:

  • When adding or renaming a field type, update its accepted type contract and its rendering path together. A type that reaches the field but not a renderer can fail at compile time or lose label and error behavior.
  • When changing numeric field bounds or display rules, keep server validation, spinbutton ARIA values, visible precision, and hook behavior aligned. The browser does not provide native min and max validation for this control.
  • When changing the pure input contract, keep file inputs value-optional and keep multiple field names consistent with the shape expected by Phoenix forms.
  • When changing names or ids for a combo box, preserve the link between the visible combobox, its label, its listbox, and the native select. Check both single and multiple form parameter shapes.
  • When changing required or invalid handling for enhanced controls, keep browser constraint validation on the real native control and keep the failure message and focus target on the visible control.
  • When changing OTP length or slot layout, keep the real input maxlength, painted slot count, sanitizing rule, and completion event in agreement.
  • When changing toggle or rating values, preserve the string round-trip from browser events and the native radio names used for form posts.
  • When changing the JavaScript-enhanced controls, update both the server-rendered initial state and the matching exported hook. The control must remain coherent before the hook mounts and after a LiveView patch.
  • When changing error translation, check both the newer Field path and the legacy Form path because they read the same application configuration.

Important failure modes

TriggerConsequenceGuard
A combo box has no id, form field, or non-empty nameThe control cannot establish stable hook and label targetsProvide one identity source before rendering the combo box
An enhanced combo box or OTP is rendered without its matching browser hookThe visible surface does not track the native value presentationInclude the Petal Components JavaScript bundle and register the exported hook
A multiple field manually mixes bare and [] namesPhoenix receives a malformed or split parameter shapeLet field or combo_box derive the multiple name and its empty fallback
A caller expects toggle_group presses to submit as form fieldsThe group sends a LiveView event but does not act as ordinary form dataHandle phx-value-toggle and assign the new server value, or use a native field control
An interactive rating omits nameRendering raises because no form value can be postedSet name for interactive ratings
A numeric field has no field, id, or nameThe label and browser hook have no stable control targetProvide a Phoenix field or an explicit id or name
A numeric field relies only on client boundsOut-of-range data can reach the changesetValidate numeric bounds on the server
A free-text combo value is not returned in the next option setThe server can discard the chosen value on the next renderPersist or re-render accepted free-text values in the option source
A field is expected to show untouched changeset errorsThe field hides those errors until Phoenix marks the input as usedUse the normal form interaction flow or pass explicit errors when early display is required

Key files

FileWhy to read it
lib/petal_components/field.exMain field API and the shared label, help, error, group, and type-selection contract
lib/petal_components/input.exPure control API and the native value behavior used inside custom layouts
lib/petal_components/form.exLegacy form helpers and the compatibility path for older applications
lib/petal_components/input_group.exShared-surface composition and addon slots
lib/petal_components/input_otp.exOne-time-code value model and completion contract
lib/petal_components/number_field.exNumeric spinbutton values, bounds, precision, and keyboard behavior
lib/petal_components/combo_box.exSearchable selection model, native form value, accessible states, and option contracts
lib/petal_components/toggle_group.exServer-driven single and multiple selection semantics
lib/petal_components/rating.exDisplay and interactive rating value models
assets/…/petal_components.jsBrowser behavior for enhanced input, OTP, range, numeric, and combo-box states
test/petal/field_test.exsBroad checks for field values, labels, errors, required state, and compound controls
test/petal/combo_box_test.exsForm, accessibility, multiple-selection, and enhanced combo-box contracts