Forms
form(schema) puts forms on the browser's own constraint validation — the same rules the browser
enforces and :invalid styles, with reactive values, errors and submit state. It is
@qatjs/form, which qatjs init lists in package.json (in an app made another way,
npm i @qatjs/form):
// signup.qx
import { form } from '@qatjs/form'
export default function Signup() {
let f = form({
email: { type: 'email', required: true, message: { valueMissing: 'Enter your email', typeMismatch: 'That is not an email' } },
password: { type: 'password', minLength: 8 },
again: { type: 'password', validate: (v, all) => v === all.password || 'The passwords differ' },
})
const save = async (values) => console.log('saving', values)
return (
<form novalidate on:submit={f.submit(save)}>
<input ref={f.field('email')} />
{if (f.errors.email)}<p class="error">{f.errors.email}</p>{/if}
<input ref={f.field('password')} />
<input ref={f.field('again')} />
{if (f.errors.again)}<p class="error">{f.errors.again}</p>{/if}
<button disabled={f.submitting}>Sign up</button>
</form>
)
}f.field(name)is aref: it sets the schema's attributes on the element (type,name,required,min/max/step,minlength/maxlength,pattern), and keeps the element andf.values[name]in sync both ways (numbers fortype: 'number', booleans for checkboxes). Radios take the samef.field(name)each, and the field is the checked one'svalue; a<select multiple>is the list of what is selected (in the browser: a post without JavaScript gives its first). A select shows the field's value also when its options come after it.- Errors are the element's native validity, as a message: the schema's
message(one string, or one per validity flag:valueMissing,typeMismatch,patternMismatch,tooShort,tooLong,rangeUnderflow,rangeOverflow,stepMismatch,badInput), else the browser's own localized message. A field's error shows once it was blurred or a submit was attempted. The element'saria-invalidfollows its validity from the start, though: a just-mounted emptyrequiredfield already saysaria-invalid="true", before any error is shown. - Messages in the user's language (
@qatjs/core/i18n): write the message as a getter, which each check reads again, so the next check speaks the language chosen meanwhile:message: { get valueMissing() { return t('todos.required') } }. A plainvalueMissing: t('todos.required')is read once, when the form is made. An error already shown changes at its field's next check (an input, a blur, a submit). validate(value, values)adds a rule (it may compare fields) throughsetCustomValidity: return a message orfalsewhen invalid.falseshows the schema'smessage, else the wordinvalid: return a message instead.f.submit(handler)is anon:submithandler: it prevents the default, shows every error, focuses the first invalid field, or runshandler(values)(plain values) withf.submittingtrue meanwhile. A submit while one is pending (Enter in a field, with the button disabled) is ignored: one request at a time. Addnovalidateto the<form>so the browser's bubbles don't block it.f.valid,f.touched[name],f.setError(name, message)(server errors, cleared when the field is edited),f.reset().
Progressive forms: they work without JavaScript
On a server-rendered route (page(p, { mode: 'server' }), also 'static' and 'island'; see
server rendering), the same form(schema) also works with JavaScript disabled, failed
or still loading. You write nothing extra: no endpoint, no second schema, no server handler:
// apply.qx (routes.js: '/apply': page('./pages/apply.qx', { mode: 'server' }))
import { form } from '@qatjs/form'
import { navigate } from '@qatjs/router'
import { applications } from '../applications.js'
export default function Apply() {
let f = form({
name: { required: true, minLength: 2, message: { valueMissing: 'Enter your full name' } },
age: { type: 'number', min: 18, required: true, message: { rangeUnderflow: 'You must be 18 or over' } },
consent: { type: 'checkbox', required: true, message: 'Confirm that the details are correct' },
})
const save = async (values) => {
const id = await applications.add(values)
navigate(`/apply/done?id=${id}`)
}
return (
<form novalidate on:submit={f.submit(save)}>
<label>Full name <input ref={f.field('name')} /></label>
{if (f.errors.name)}<p class="error">{f.errors.name}</p>{/if}
<label>Age <input ref={f.field('age')} /></label>
{if (f.errors.age)}<p class="error">{f.errors.age}</p>{/if}
<label><input ref={f.field('consent')} /> The details are correct</label>
{if (f.errors.consent)}<p class="error">{f.errors.consent}</p>{/if}
<button>Apply</button>
</form>
)
}- The markup. The server writes what the browser's own submit needs:
method="post" action="/apply?qat-form=0"on the<form>(the number is the form's position on the page), andname,type, the schema's constraint attributes and the current value on each field. - Without JavaScript, the browser posts the form to that URL. The server renders the page with
the posted values and validates them with the same schema: the browser's constraint-validation
rules (
required,type,pattern,minLength,min/max/step, …) and yourvalidatefunctions.- Invalid: the page comes back (status 422) with
f.errorsfilled, the values as typed, andaria-invalidon the fields. The messages are your schema'smessages. Without one, the server uses Chrome's English message, while the browser shows its own localized one; givemessagefor the same words on both sides. - Valid: your
f.submit(handler)handler runs on the server.navigate(to)in it is the redirect (303), andf.setError(name, message)sends the page back with that error. Without either, the answer is a 303 back to the page (POST/redirect/GET), so a reload never submits twice. The handler gets the same plain values as in the browser: numbers fortype: 'number', booleans for checkboxes. - Only the page's own post is taken; any other is refused with 403. When the browser
sends
Sec-Fetch-Site, it decides:same-originonly (a page's own post underReferrer-Policy: no-referrersaysOrigin: nullandsame-origin, and is taken; a sandboxed frame saysnullandcross-site). Without it (Safari before 16.4, a client that is not a browser), theOrigin, else theReferer's origin, must be the app's own.null, or neither header, is refused.
- Invalid: the page comes back (status 422) with
- With JavaScript, the page resumes and the same nodes become the reactive form: errors as the user types, focus on the first invalid field, and the handler runs in the browser with no page load. What the user typed before the page resumed is kept. A submit made before then is queued and replayed once the form has resumed.
- One handler, both sides. The handler runs wherever the submit happens, so write it to run
in both places: call your API through a module (
applications.add), as a routeloaddoes, notwindoworlocalStorage.navigate()andf.setError()work in both places.
This is the default for public-sector forms and for any form that must work for everyone:
render its route on the server and the form needs no JavaScript, as progressive enhancement
(the GOV.UK Service Manual's rule for public services) asks. The one exception is @qatjs/form/offline: it sends its
submissions itself, so its route stays 'client'.
The validation rules are tested to agree with Chrome's own, row by row, from one table
(packages/server/test/form-validity.cases.js). The server side is @qatjs/server/form: a server
build includes it when the app depends on @qatjs/form, and the browser gets none of it. The form
core grows by 65 B for it (1.20 kB, pnpm size).
Offline forms
@qatjs/form/offline is a form(schema, options) that sends itself. With offline: true, a
submission made without network waits in IndexedDB and is sent, in order, when the network
returns:
// contact.qx
import { form } from '@qatjs/form/offline'
export default function Contact() {
let f = form(
{ email: { type: 'email', required: true }, message: { required: true } },
{
action: '/api/messages',
offline: true,
onSubmitted: (reply, values) => console.log('sent', values.message, reply),
onFailed: (error, values) => console.log(error.status, error.message),
},
)
return (
<form novalidate on:submit={f.submit()}>
<input ref={f.field('email')} />
<textarea ref={f.field('message')} />
<button disabled={f.submitting}>Send</button>
{if (f.queued)}<p role="status">{f.queued} queued: sent when you are back online</p>{/if}
{if (f.error)}<p role="alert">{f.error}</p>{/if}
</form>
)
}f.submit()validates like the plain form, then sends the values as JSON toaction(methoddefaults to'POST';headersare added).f.submit(handler)is still the plain form's submit.- Results go to
onSubmitted(result, values)for a 2xx response (resultis the JSON body, or its text), and toonFailed({ status, message }, values)for any other.messageis the body'smessage, else its text. A 409 also setsf.errorto that message: the server says the submission conflicts, so the form shows it. The next submit clearsf.error. - Without network: when
navigator.onLineis false, orfetchfails, the submission goes to the queue andf.queuedcounts this form's waiting submissions. The count stays right across a reload, and across tabs. - Replay, oldest first, under a Web Lock, so only one replayer runs at a time. A page replays
on the
onlineevent, and at start when something is waiting. With aqatjs compress --pwabuild, the service worker also replays on Background Sync, even with no page open. A replay stops at the first network failure, which keeps the order. Its results go to the callbacks of every open form with thatname. name(default:`${method} ${action}`) routes the results.queuereplaces the IndexedDB store (idbQueue) with any{ add, all, delete }, for tests.- Without
offline: true, a network failure isonFailed({ status: 0, … }). - The queue keeps the whole request, its
headerstoo, in IndexedDB in the clear, and replays it later as it was. Do not put a token inheaders(anAuthorizationheader would sit on the device and be sent after it may have expired): let a cookie carry the session, or the server answer the replay's 401 throughonFailed.
The entry is separate: an app that does not import it pays nothing. The form core is 1.20 kB;
@qatjs/form/offline adds about 0.94 kB.