Validate the same rules on the server
What it combines
- A serialisable form config —
required,min,minLength,email… compiled to Zod (Validation) validateFormData/buildFormSchemafrom@saastro/forms/validation— the same compiler the browser uses, runnable anywhere- A Cloudflare Worker — it receives the submission and answers
422with errors keyed by field
Submit the form, then edit the raw request below and send it: it skips the browser and the server code rejects it. The server code runs here in the page; nothing is sent.
A request that skips the browser (edit it, then send):
import { FormBuilder } from '@saastro/forms';
import { type ValidatableForm, validateFormData } from '@saastro/forms/validation';
/** One config, used by the browser form AND by the server. Serialisable rules only. */
export function createConfig() {
return FormBuilder.create('signup')
.layout('manual')
.columns(12)
.addField('email', (f) =>
f.type('email').label('Email').required().email().columns({ default: 12 }),
)
.addField('age', (f) =>
f.type('number').label('Age').required().numberRange(18, 120).columns({ default: 12 }),
)
.addField('username', (f) =>
f.type('text').label('Username').required().minLength(3).columns({ default: 12 }),
)
.addStep('signup', ['email', 'age', 'username'])
.initialStep('signup')
.build();
}
/**
* The server half, framework-free: takes the parsed request body, returns the
* status and JSON to answer with. `validateFormData` only needs `fields` (and
* optional cross-field rules), so a Worker can load the config from KV/D1/JSON
* instead of importing the builder. It imports only zod: no React in the Worker.
*/
export function handleSignup(body: unknown): { status: number; json: unknown } {
// `FormConfig.fields` also admits custom field types, which `ValidatableForm` does not: cast.
const result = validateFormData(createConfig() as unknown as ValidatableForm, body);
if (!result.success) {
// errors: { email: ['…'], age: ['…'], _form: ['…'] }
return { status: 422, json: { ok: false, errors: result.errors } };
}
// Unknown keys are stripped: store result.data, never the raw body.
return { status: 200, json: { ok: true, data: result.data } };
}
/** The Cloudflare Worker that wraps it. */
export default {
async fetch(request: Request): Promise<Response> {
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const { status, json } = handleSignup(await request.json().catch(() => null));
return Response.json(json, { status });
},
};The code
The Code tab above holds both halves: createConfig() for the form and handleSignup(body) plus the Worker fetch handler for the server. The browser side is a normal <Form config={createConfig()} />; the Worker is the default export, deployed with Wrangler.
import { validateFormData } from '@saastro/forms/validation';
const result = validateFormData(form, body);
if (!result.success) return Response.json({ ok: false, errors: result.errors }, { status: 422 });
How it works
- One source of truth — the rules a form ships are compiled to Zod identically on both sides, so what the browser accepts the server accepts, and the other way round.
- Lean import —
@saastro/forms/validationis React-free and pulls onlyzod, so it fits in a Worker. - Result shape —
{ success: true, data }or{ success: false, errors }, witherrorsasRecord<field, string[]>. A rule that spans several fields reports under_form. - Unknown keys are stripped —
datacontains only the fields the config declares; theisAdminkey in the demo’s request does not reach it. buildFormSchema(form)returns the Zod object when you want to compose it yourself (.extend,.safeParseAsync…).
Caveats
- Only serialisable rules travel — a field whose
schemais a hand-written Zod object, or a form-levelformSchema, exists only in code. Keep the server onValidationRulesandcrossFieldRulesif the Worker loads the config as JSON. - Use the validation methods — on a number field,
.min()and.max()set the field’s props and the server does not enforce them;.numberRange(min, max)writes the rule both sides compile, which is why the recipe uses it. - Plugin validators don’t run —
customValidatorsregistered through plugins are a client feature. Re-implement them on the server. - Validation is not authorisation — it checks shape, not who is calling. Add your own auth, rate limiting and bot protection.
- Conditionally hidden fields are skipped —
validateFormDataevaluates each field’shiddencondition against the submitted values and does not validate (or return) the ones that are hidden. A field with a literalhidden: trueis a hidden value field and is still validated. Pass{ validateHidden: true }as the third argument to validate hidden-by-condition fields too. - Keep both sides in step — deploy the Worker and the page from the same version of the config; an older client can post fields a newer Worker rejects.
Variations
- Load the config from JSON (
validateFormConfigchecks it first) instead of importing the builder in the Worker. - Add
crossFieldRules(matches,requiredIf…) once: the browser and the server both enforce them. - Return
result.errorsas-is and render them next to the fields on the client.