# Validate the same rules on the server

URL: https://docs.forms.saastro.io/docs/recipes/server-validation
> Reuse a form's validation rules in a Cloudflare Worker with validateFormData, so a request that skips the browser is rejected by the same rules.

# Validate the same rules on the server

## What it combines

- **A serialisable form config** — `required`, `min`, `minLength`, `email`… compiled to Zod ([Validation](/docs/validation))
- **`validateFormData` / `buildFormSchema`** from `@saastro/forms/validation` — the same compiler the browser uses, runnable anywhere
- **A Cloudflare Worker** — it receives the submission and answers `422` with errors keyed by field

```tsx
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.

```ts
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/validation` is React-free and pulls only `zod`, so it fits in a Worker.
- **Result shape** — `{ success: true, data }` or `{ success: false, errors }`, with `errors` as `Record<field, string[]>`. A rule that spans several fields reports under `_form`.
- **Unknown keys are stripped** — `data` contains only the fields the config declares; the `isAdmin` key 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 `schema` is a hand-written Zod object, or a form-level `formSchema`, exists only in code. Keep the server on `ValidationRules` and `crossFieldRules` if 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** — `customValidators` registered 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** — `validateFormData` evaluates each field's `hidden` condition against the submitted values and does not validate (or return) the ones that are hidden. A field with a literal `hidden: true` is 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 (`validateFormConfig` checks 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.errors` as-is and render them next to the fields on the client.

## Related

- [Validation](/docs/validation)
- [Submit & Actions](/docs/submit)
- [Multi-step lead form with a webhook](/docs/recipes/multi-step-webhook)
