Form validation
Define shared schemas, cast native values, report nested issues, and revalidate inputs on the server.
KetJS form validation is a browser-safe contract rather than a component convention. A schema casts native
form values, applies field and cross-field constraints, and returns machine-readable issues. The same schema
runs in @ketvietlab/ketjs-view and on the server through @ketvietlab/ketjs.
Requires KetJS 0.4.0
Nested contracts, edit sessions and transactional form actions require KetJS and ketjs-view 0.4.0 or later. The 0.3.0 packages include the legacy schema/controller APIs, but do not export
defineFormContract,createFormSession,attachFormordefineFormAction. Keep the framework packages used by an application on the same released version.
This guide covers shared schemas and issues. For browser drafts, submit state, native controls and render subscriptions, read Forms and edit sessions in the ketjs-view section. For atomic server writes, revision checks and durable receipts, read Transactional form actions.
Client validation improves feedback but is never an authorization boundary. Validate again on the server before calling a function or writing data.
Define one schema#
// File: src/modules/example/forms.ts
import { defineFormSchema, validationIssue } from '@ketvietlab/ketjs-view'
type Signup = {
email: string
age: number
password: string
confirmation: string
}
export const signupForm = defineFormSchema<Signup>({
fields: {
email: {
type: 'text',
required: true,
trim: true,
pattern: /^[^@]+@[^@]+$/,
},
age: { type: 'int', required: true, min: 18 },
password: { type: 'text', required: true, minLength: 8 },
confirmation: { type: 'text', required: true },
},
unknown: 'reject',
validate: (values) =>
values.password === values.confirmation
? true
: validationIssue(
'confirmation',
'confirmation',
'signup.passwordConfirmation',
),
})Field types are text, id, ref, int, float, decimal, bool, date, datetime, json,
object, array, and record.
An int value must be a plain decimal integer within the safe integer range, so 0x10, 1e3 and 1.0
are issues rather than numbers. A datetime value must be ISO-8601 date-time text such as
2026-10-21T10:00, with an optional offset; the browser's own date parser is never consulted, so the form
accepts what the server changeset accepts.
Constraints include required, min, max, minLength, maxLength, pattern, and oneOf. Set
multiple: true for repeated controls such as a multi-select. Optional empty values are omitted from the
normalized result.
Unknown fields are dropped by default, matching the allow-list behavior of changesets. Use
unknown: 'reject' at boundaries where an unexpected control should be reported as an error.
Validate and inspect issues#
// File: src/modules/example/forms.ts
import { validateForm, valuesFromFormData } from '@ketvietlab/ketjs-view'
const raw = valuesFromFormData(new FormData(form))
const result = validateForm(signupForm, raw)
if (!result.valid) {
console.log(result.fieldErrors.email)
console.log(result.formErrors)
}valuesFromFormData() preserves repeated names as arrays instead of silently discarding entries.
validateForm() returns normalized values, flat issues, grouped fieldErrors, form-level
formErrors, and the names of dropped inputs.
Every issue has a stable transport shape:
// File: src/modules/example/forms.ts
type ValidationIssue = {
field: string | null
code: string
messageKey: string
params: Record<string, unknown>
}field: null identifies a whole-form error. Render messageKey through the application's translator and
use params for interpolation. Do not branch on translated text.
Declare nested values explicitly#
// File: src/modules/catalog/variant-form.ts
import { defineFormContract } from '@ketvietlab/ketjs-view'
export type VariantDraft = {
variants: Array<{
rowKey: string
id: string | null
weight: string
active: boolean
}>
}
export const variantForm = defineFormContract<VariantDraft>('catalog.variants.v1', {
fields: {
variants: {
type: 'array', required: true, key: 'rowKey', maxItems: 500,
items: {
type: 'object',
fields: {
rowKey: { type: 'id', required: true },
id: { type: 'id', required: true, nullable: true },
weight: { type: 'decimal', required: true, min: 0 },
active: { type: 'bool', required: true },
},
},
},
},
})object.fieldsvalidates a fixed object;array.itemsvalidates every item;record.entriesvalidates dictionary values, such as an attribute-ID to selected-value-ID map.- A malformed list is rejected. It never becomes
[]. An explicitly submitted[]is valid unlessminItemsforbids it; deciding whether it archives existing records belongs to the command. keyrequires unique, nonempty string row identities. KeeprowKeystable when a new row receives its databaseid. Neither a row key nor a submitted ID establishes ownership or permission.- Unknown fields are rejected by default in a contract, including nested objects. A nested rule can
explicitly override
unknown. LegacydefineFormSchema()retains its drop-by-default behavior. nullable: truepreserves explicit null.empty: 'null'with nullable converts an empty string to null;empty: 'keep'preserves an optional empty string.defaultapplies only when absent. Missing, null, false, and an empty list are distinct. Do not clear disabled or omitted fields by accident.- Structured fields default to at most 1,000 entries.
minItemsandmaxItemsbound arrays, objects and dictionaries. Validation also bounds recursive depth and total field visits. Domain code must separately bound combination generation before allocating the Cartesian product. - Use the contract's
validatecallback for shared, pure cross-field rules. It receives normalized partial values; malformed structured fields prevent that callback from running. Database uniqueness, record ownership, permissions and current business state remain server checks.
Nested issues keep an indexed field, for example variants.2.weight, and add a stable path,
for example ['variants', { key: 'draft-42' }, 'weight']. formIssuePath(contract, submittedValues, field)
maps domain errors with the submitted snapshot. Never resolve an old index against a newly sorted list.
For dictionary keys containing dots, use the explicit path rather than inventing dotted field names.
Validate on the server#
Use assertForm() when a route should stop immediately on invalid input:
// File: src/modules/example/forms.ts
import { assertForm, json } from '@ketvietlab/ketjs'
const values = assertForm(signupForm, rawBody)
await createAccount(values)
return json({ ok: true })FormValidationError is serialized by the KetJS HTTP server with status 422, code
E_FORM_INVALID, and the same issues, fieldErrors, and formErrors shape used in the browser.
Use invalidForm(result) when a route prefers to return rather than throw:
// File: src/modules/example/forms.ts
const result = validateForm(signupForm, rawBody)
if (!result.valid) return invalidForm(result)Function signature failures also return HTTP 422 with code E_INVALID_INPUT and structured field
issues. Authentication, authorization, unknown routes, and other request failures keep their existing
status codes.
Refuse a submit on a server-rendered screen#
assertForm() and invalidForm() answer a program: they end the request with 422 and a JSON body. A
server-rendered screen answers a person, who is still looking at the form they typed into, so the same
submit has to render that screen again rather than replace it:
- keep the form or dialog open, and refill it with what was submitted — not the stored row, and not the
normalized values, because
validateForm()drops the invalid ones that the person has to correct; - put each issue on the control it names, with
aria-invalid, so it reaches a screen reader as well as an eye; - decide that the submit was refused from the presence of any issue, not from a count of form-level messages: a refusal made only of field issues has no form-level sentence to count.
A design system built on KetJS may package these rules for its screens; such helpers are documented with that design system rather than here.
Changesets and business validation#
Form schemas validate presentation input. Changesets still own model casting, mass-assignment protection, and persistence validation. Convert existing changeset errors when a route needs the shared transport shape:
// File: src/modules/example/forms.ts
const changes = ctx.change('sales.Order', values).cast(['number']).required(['number'])
if (!changes.valid) {
return invalidForm(issuesFromFieldErrors(changes.errors))
}Database-backed checks such as uniqueness, current inventory, or permissions remain server-only. Return
their outcome as ValidationIssue values and call formState.applyServerIssues(problem) in an enhanced
browser flow.
Browser forms and server actions#
The browser and transaction guides now have their own navigation entries. Existing links to their former sections remain available here:
Manage browser form state covers createForm,
reactive validation, touched fields and the low-level submit handler.
Transactional edit forms covers the form session, accepted baselines, refusal, conflict and unknown-outcome retry.
Commit the command and its receipt together covers the server action and its database transaction.
Attach native controls or a custom editor covers DOM binding, field errors, submitters and lifecycle ownership.
Render subscriptions and cost covers whole-draft subscriptions, primitive selectors, adapter work and the measured performance limits.
Migrate a complex editor describes adoption without replacing the consumer's layout or domain commands.