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 freshlyfilled record).ValidatedAll: validates every key (including loaded row invariants) without settingattemptedor 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 isrequiredwhen none of those decode. PlainSchema.Stringaccepts""; addSchema.isMinLength(1)to require text. - Option keys:
Schema.OptionFromNullOr(Schema.String)renders as a text control, validates the inner schema, submitsOption.some/Option.none, and fills fromOption. - Numbers: unparseable text reads
"Enter a number"; whitespace-only text counts as empty rather than zero. - Submit (
Submitted): validates every key and setsmodel.attempted. Cross-field schema errors land inmodel.errorsuntil the next edit;attemptedclears onResetorfill.
Entity invariants and editing an existing row
- State invariants on submit:
Submittedevaluates the Entity'sEntity.invariantrules over the decoded input (Entity.judgeInput), placing failures inmodel.marksbeside namedpathkeys (ormodel.errorswhen unpathed). Any edit clearsmarksso fixing either side of a rule clears the error.Message.Refusedsets 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 viaform.over(model, Entity.rowFrom(entity, loaded))(selecting extra fields withEntity.selectFor(input, { also: Entity.judgedBy(input) })). Invariants then judge the merged row (includingbefore.statustransition rules) on every edit once all participating form keys have been touched (model.reached).foldkit-crudwires this automatically. - Custom primitive operators: pass
{ operators }toForm.makewhen invariants use operators outsideOperators.kernel(nested forms inherit the parent table by default).
Checking whether a form can submit
| Query | True 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:
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
Validatingwhile running andValidwhen passing.Adding service requirements (
Form.checks): when a check needs a service such asRemoteClient, attach it with theForm.checkspipe step so TypeScript infers the Bundle's service requirements (R):tsconst 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, orsubject. Submitting while a check runs holdssubmitPendingand emits{ _tag: 'Submitted', value }once checks pass (passsubmitWaits: falseto refuse submits while checks run instead).Testing and
context.subject: checks run throughPostForm.Check(resolve in stories viaCommand.resolve(PostForm.Check, PostForm.Message.Checked({ key, draft, error }))). When editing an existing record whoseidsits outside the form input, sendMessage.About({ subject: { id } })once on open to populatecontext.subject.
Messages
Attach custom field error messages directly on Effect Schema checks:
Schema.String.check(Schema.isMinLength(3, { message: 'Give it at least 3 letters' }))Customize the form's built-in messages with messages:
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,
},
})| Message | Said when | Default |
|---|---|---|
required(field) | Empty draft on a required key | Required |
unparsed(field) | Draft text fails control parsing | Kind's unparsed (Enter a number) |
invalid(field, message) | Key schema rejects the draft | message |
form(message) | Cross-key input schema fails | message |
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:
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 & ViewWordsPass the same words object to Form.make, placed.view, and PostTable;
fillWords(template, values) performs the substitution.