View as Markdown

Components

Form

Form validation with @salmonui/inputs/form - one rule vocabulary with the Data Grid, native constraint validation, server errors and React 19 actions.

Form validation is declarative: rules live on each field's validation prop (or native constraint attributes), and Form renders a native <form> that validates its fields on submit. There is no validator instance.

import { useActionState } from 'react';
import { Form } from '@salmonui/inputs/form';
import { TextField } from '@salmonui/inputs/text-field';
import '@salmonui/inputs/form/styles.css';

const [state, action] = useActionState(saveUser, { errors: {} });

<Form action={action} validationErrors={state.errors}>
  <TextField name="email" label="Email" validation={{ required: true, email: true }} />
  <button type="submit">Save</button>
</Form>

Form validation

Open demo

Field rules in the Data Grid vocabulary, native constraints, an equalTo rule, an async rule and a blocked submit that focuses the first invalid field.

Try “admin”

Rules

validation takes the Data Grid column.validation vocabulary, compiled by the same compileValidationRules from @salmonui/core/validation: required, min, max, range, minLength, maxLength, rangeLength, number, digits, email, url, date, dateIso, creditcard, tel, pattern (a regular expression; a partial match passes, so anchor it) and validate. Built-in rules are synchronous and allocate nothing on success (well under 0.05 ms per field per keystroke).

  • Messages: [argument, message] per rule, validation.messages, then localeText keys shared with the Data Grid (validationRequired, validationMin, ...).
  • Custom rules: validate(value, ctx) returns a message, null / true (valid) or false (the validate message); [fn, message] or an array of functions; promises are allowed. ctx is { name, formData, isNew: false }, so a "must equal" rule is validate: [(v, ctx) => v === ctx.formData?.get('password'), 'Passwords differ'].
  • Changing a field's validation prop replaces its rules. Inline objects keep their compiled form while they are shallow-equal.
  • Native attributes (required, minLength, maxLength, min, max, step, pattern, type) are honored and reported with the same messages.

Validation rules and events

Open demo

Form validation with per-rule, validation.messages and localeText messages, native HTML constraints read as rules, rules swapped at runtime, error text from a function, onBeforeValidate and onValidate, and the native reportValidity and requestSubmit entry points.

Per-rule message for minLength; localeText for required
validation.messages overrides the maxLength text
Native required, pattern, minLength and maxLength; the error text comes from a function
Native type="url": type "example" and blur
Optional
No events yet.

One rule engine for forms and grids

Open demo

The same validation rule object on a Form field and a Data Grid column, compiled by the same compileValidationRules, and a timing of the built-in rules showing the per-keystroke cost and the shared empty result on success.

Same rules as the grid's SKU column
Id
SKU
Name
1
TEA-101
Green tea
2
COF-202
Espresso beans
3
MUG-303
Travel mug
(press "Time the rules")

When errors show

validateOn (on Form or per field): 'blur' (default) shows errors after the first blur or a submit attempt, the :user-invalid model, and then updates them on every change; 'change' shows them while typing; 'submit' waits for a submit attempt. Each keystroke re-runs only its own field's rules and re-renders that field only when its shown errors change.

Results are written to the native input with setCustomValidity, so form.reportValidity(), requestSubmit(), input.reportValidity() and :invalid agree with what Salmon shows.

Submitting

  • validationBehavior: 'native' (default) blocks an invalid submit and focuses the first invalid field in document order; 'aria' marks the fields and lets the submit proceed, for server-validated forms.
  • Async rules show data-validating on the field; a submit waits for them and then submits again or focuses the first error.
  • onBeforeValidate(event) runs before client validation; event.preventDefault() skips it for that submit. onValidate({ valid, errors }) reports the outcome keyed by field name.
  • validationErrors (server errors keyed by name, for example from useActionState) show as field errors until the field's value changes; they survive the automatic reset React performs after an action.
  • React 19 action, useFormStatus and useActionState work unchanged; with a server action the form also submits before hydration.
  • A native reset restores every uncontrolled field and clears shown errors.

Server errors and actions

Open demo

A Form driven by a React 19 action and useActionState - server errors shown as field errors until the value changes, blocking or non-blocking client validation, and a submit button reading useFormStatus.

@

Try the handle “ada” or an @example.com address.

Fields in a form

Open demo

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

Required: an incomplete number blocks the submit
Delivery slot
Delivery window (hours)
Priority
Signature
Optional: submitted as a PNG data URL

Change some fields, then submit or reset.

(nothing submitted yet)

Required marks

requiredMark on Form puts a decorative asterisk before the label of every field inside whose control is required (required or aria-required), including Select and Combobox labels:

<Form requiredMark>
  <TextField name="customer" label="Customer" required />
  <Select name="status" label="Status" required data={statuses} />
  <TextField name="note" label="Note" />
</Form>
  • The mark is CSS only (@salmonui/inputs/form/styles.css): a ::before with empty alternative text in the danger text color, at the inline start of the label (so it moves to the right under dir="rtl"). It is never announced; screen readers hear "required" once, from the control.
  • Field requiredMark marks one custom field; requiredMark={false} opts a field out under a marking Form. The rule follows the control's required state live, so a field that becomes optional loses the mark.
  • Any element with data-required-mark="true" (a <fieldset>, a section of a page) marks the fields inside it the same way.

Unsaved changes: useFormState

useFormState() from @salmonui/inputs/form/state tracks whether a form differs from its initial values. It works with the native FormData model: no field is controlled or registered, and the initial values are the fields' defaultValues.

import { Form } from '@salmonui/inputs/form';
import { useFormState } from '@salmonui/inputs/form/state';

function OrderEditor({ order, onClose }) {
  const form = useFormState();
  const confirm = useConfirm();
  const requestClose = async () => {
    if (form.isDirty && !(await confirm({ title: 'Discard unsaved changes?', tone: 'danger', confirmLabel: 'Discard', cancelLabel: 'Keep editing' }))) return;
    onClose();
  };
  return (
    <Drawer open title="Edit order" onOpenChange={(open) => open || void requestClose()}>
      <Form ref={form.ref} requiredMark onSubmit={save}>
        <Drawer.Body>
          <TextField name="customer" label="Customer" required defaultValue={order.customer} />
        </Drawer.Body>
        <Drawer.Footer>
          {form.isDirty ? (
            <>
              <Button variant="outline" onClick={form.reset}>Discard</Button>
              <Button type="submit">Save</Button>
            </>
          ) : (
            <Button variant="outline" onClick={requestClose}>Close</Button>
          )}
        </Drawer.Footer>
      </Form>
    </Drawer>
  );
}
  • ref: attach to the form (<Form ref={form.ref}> or a plain <form ref>). When the form mounts, its FormData is the snapshot of initial values; a form that mounts again (a drawer opened again, a key change after a save) takes a new snapshot and starts clean.
  • isDirty, dirtyFields (the names that differ, in form order) and isFieldDirty(name). A field is dirty when its submitted values differ from the snapshot, so changing a value back makes it clean again; an unchecked checkbox and a disabled field submit nothing, so checking one or enabling a field with a value makes it dirty. Files compare by name, size and date.
  • reset() calls form.reset(): native controls and every Salmon field return to their defaultValue, shown errors clear, and the state is clean. A controlled field whose value the parent holds stays dirty until the parent resets it.
  • The hook listens to input and change events on the form and observes its controls, so the hidden inputs and options of custom-drawn fields (Select, NumberField, ColorPicker, ...) count too. One FormData read per change; the form's fields do not re-render, only the component that calls the hook, and only when the set of dirty names changes.
  • Fields outside the <form> element (a form="id" attribute) are not tracked. On the server the state is clean.
  • Its own subpath, so @salmonui/inputs/form does not grow for apps that do not use it.

Edit drawer with unsaved changes

Open demo

An order editor in a Drawer built on useFormState - Save and Discard appear only while the form is dirty, closing a dirty form asks through useConfirm, required labels carry a mark, and statuses show as status dot badges.

OrderCustomerStatusActions
ORD-1042Ada LovelacePaid
ORD-1043Grace HopperPending

Performance

Every Inputs subpath has a gating JavaScript and stylesheet row in npm run bundle:check. A keystroke re-renders only the edited field, and dragging a Slider or drawing a signature causes no React render.

Inputs render cost

Open demo

Render counters around text, number and masked fields show that typing re-renders only the edited field, a Slider drag and a signature stroke run without React renders, and the QueryBuilder subpath loads as its own chunk only when used.

Demo (parent) renders: 0
Text owner renders: 0
Number owner renders: 0
Masked owner renders: 0
last keystroke: (type to measure)Controlled owner renders: 0
Uncontrolled slider
Uncontrolled signature
pointer moves: 0, Slider renders: 0, SignaturePad value changes: 0

Error placement

Every field renders its error below the control with the id its aria-errormessage points at; errorMessage replaces the text or receives { errors }. For a custom layout, render FieldError yourself in a Field with errorPlacement="manual".

SSR

Form renders a native <form noValidate> with the same markup on the server and the client. Before hydration a submit is a plain native submit (a server action still runs); the Salmon rules run once the page is hydrated.

Design notes

  • there are no state class options; state classes would duplicate ARIA state, so state is [data-invalid] and [aria-invalid="true"]. Style invalid fields with [data-invalid].
  • there is no skip list; a class-based skip list couples markup and validation. Fields without rules are not validated and disabled fields are skipped natively. Omit validation or set disabled.
  • there is no method that looks an input up by name; the platform already does. Use form.elements.namedItem(name) or a ref.

API

Form prop Type Default
validationBehavior 'native' | 'aria' 'native'
validateOn 'blur' | 'change' | 'submit' 'blur'
validationErrors Record<string, string | string[]>
onBeforeValidate (event: { form, preventDefault() }) => void
onValidate ({ valid, errors }) => void
requiredMark boolean false
action, onSubmit, onReset, native form props

ref is the <form>. Salmon sets noValidate so the browser's own bubbles stay off; pass noValidate={false} to get them back.

Field, FieldError, FieldDescription and the shared field props are documented on Field. Full signatures: @salmonui/inputs/form API reference.