Form / foldkit-form

Validation

Every key validates against the input's own schema for that key, allowing an operation to be stricter than the underlying Entity.

When fields validate

  • Changed: validates the edited key immediately.
  • Blurred: leaves untouched fields unjudged until submit so tabbing past a required field stays quiet, while clearing and blurring a previously edited field shows its error.
  • Validated({ key }): validates one key on demand (useful for showing errors on a freshly filled record).
  • ValidatedAll: validates every key (including loaded row invariants) without setting attempted or submitting, for pages submitting multiple forms together.
  • No-op updates: validations that leave state unchanged return the same Model reference to skip redundant redraws.

Empty values, numbers, and submits

  • Empty drafts ("" or []): resolved in order against what the schema accepts — omitted key (optionalKey/optional), Option.none(), null, or the empty value itself. A key is required when none of those decode. Plain Schema.String accepts ""; add Schema.isMinLength(1) to require text.
  • Option keys: Schema.OptionFromNullOr(Schema.String) renders as a text control, validates the inner schema, submits Option.some/Option.none, and fills from Option.
  • Numbers: unparseable text reads "Enter a number"; whitespace-only text counts as empty rather than zero.
  • Submit (Submitted): validates every key and sets model.attempted. Cross-field schema errors land in model.errors until the next edit; attempted clears on Reset or fill.

Entity invariants and editing an existing row

  • State invariants on submit: Submitted evaluates the Entity's Entity.invariant rules over the decoded input (Entity.judgeInput), placing failures in model.marks beside named path keys (or model.errors when unpathed). Any edit clears marks so fixing either side of a rule clears the error. Message.Refused sets a mark while the key still holds the refused value.
  • Judging against an existing row (form.over): edit forms often set a subset of fields on an existing row. Pass the loaded, encoded row via form.over(model, Entity.rowFrom(entity, loaded)) (selecting extra fields with Entity.selectFor(input, { also: Entity.judgedBy(input) })). Invariants then judge the merged row (including before.status transition rules) on every edit once all participating form keys have been touched (model.reached). foldkit-crud wires this automatically.
  • Custom primitive operators: pass { operators } to Form.make when invariants use operators outside Operators.kernel (nested forms inherit the parent table by default).

Checking whether a form can submit

QueryTrue when
form.isValid(model)Every key and row passes; async checks idle
form.canSubmit(model)Invalid errors clear; async checks may still run
form.value(model)Some(input) when all valid; otherwise None

Read form.isValid and form.value when submitting manually; bind a Save button's enabled state to form.canSubmit.

Field state uses foldkit/fieldValidation's Field (NotValidated, Validating, Valid, Invalid with errors). See Errors and failures for how form validation meets server refusals.

Checks: rules only something else can answer

Async checks (such as checking whether a slug is taken on the server) return an Effect yielding an error string or undefined:

ts
import { Effect } from 'effect'

const PostForm = Form.make('PostForm', Entity.input(Post, PostInput), {
  checks: {
    // The decoded value, and whatever else in the form decodes right now.
    slug: (slug, { values }) =>
      isSlugTaken(slug, values.id).pipe(
        Effect.map(taken => (taken ? `"${slug}" is taken` : undefined)),
      ),
  },
  debounce: '300 millis',
})
  • Runs after schema validation: checks only see decoded values (numbers, not raw strings). Keys read Validating while running and Valid when passing.

  • Adding service requirements (Form.checks): when a check needs a service such as RemoteClient, attach it with the Form.checks pipe step so TypeScript infers the Bundle's service requirements (R):

    ts
    const CheckedForm = Form.make('PostForm', Entity.input(Post, PostInput), {
      debounce: 0,
    }).pipe(Form.checks({ slug: isAddressFree }))
  • Stale results and waiting submits: edits re-run checks after debounce, discarding results for outdated drafts, values, or subject. Submitting while a check runs holds submitPending and emits { _tag: 'Submitted', value } once checks pass (pass submitWaits: false to refuse submits while checks run instead).

  • Testing and context.subject: checks run through PostForm.Check (resolve in stories via Command.resolve(PostForm.Check, PostForm.Message.Checked({ key, draft, error }))). When editing an existing record whose id sits outside the form input, send Message.About({ subject: { id } }) once on open to populate context.subject.

Messages

Attach custom field error messages directly on Effect Schema checks:

ts
Schema.String.check(Schema.isMinLength(3, { message: 'Give it at least 3 letters' }))

Customize the form's built-in messages with messages:

ts
const Localized = Form.make('Rename', Entity.input(Post, RenameInput), {
  messages: {
    required: field => `${field.label} is missing`,
    unparsed: field => `${field.label} must be a number`,
    invalid: (field, message) => `${field.label}: ${message}`,
    form: message => message,
  },
})
MessageSaid whenDefault
required(field)Empty draft on a required keyRequired
unparsed(field)Draft text fails control parsingKind's unparsed (Enter a number)
invalid(field, message)Key schema rejects the draftmessage
form(message)Cross-key input schema failsmessage

field carries the key, its label, and its control.

Words as text, in one place

Every message entry also accepts a template string ('{label} is required', with {label}, {key}, and {message} placeholders), which keeps words serializable in view inputs and lets you share one catalogue across packages:

ts
import type { FormMessages } from 'foldkit-form'
import type { ViewWords } from 'foldkit-mixins-crud'
import type { FormViewWords } from 'foldkit-mixins-form'

export const words = {
  required: '{label} is required', // foldkit-form
  submit: 'Save', // foldkit-mixins-form
  add: 'Another {label}',
  yes: 'Live', // foldkit-mixins-crud
  empty: 'No posts yet.',
} satisfies FormMessages & FormViewWords & ViewWords

Pass the same words object to Form.make, placed.view, and PostTable; fillWords(template, values) performs the substitution.