# Validation with Zod – Form Builder

Build a Zod schema from a form's definition, using the builder's rules and error keys.

The sample project turns a resolved form into one [Zod](https://zod.dev) schema, using the same rules and error keys as the builder. Find it in [`examples/form-builder-next`](https://github.com/san26786/geecon-contentful/tree/main/examples/form-builder-next), in `src/lib/form-builder/zod.ts`. See [Reading forms](https://contentful.geeconglobal.com/apps/form-builder/docs/reading-forms) to get a resolved form.

Zod checks what a visitor sends. Your server should run the same schema on every submission, because browser checks can be bypassed. The app doesn't receive or store submissions.

## One schema per set of answers

`toZodSchema(form, values)` takes the current answers, because they decide which fields are shown. A field that `isVisible` hides isn't checked and isn't required. Build the schema again whenever the answers change, and on the server build it from the submitted answers.

```ts title="examples/form-builder-next/src/lib/form-builder/zod.ts (trimmed)"
export function toZodSchema(form: ResolvedForm, values: Record<string, unknown> = {}, now: Date = new Date()) {
  const items = form.definition.pages.flatMap((p) => p.items);
  const fields = items.filter((i): i is FormField => !isLayout(i));
  const shape = Object.fromEntries(fields.map((f) => [f.id, z.unknown().optional()]));
  return z.object(shape).superRefine((answers, ctx) => {
    for (const field of fields) {
      if (!isVisible(field, values, items)) continue;
      const fail = failure(field, answers[field.id], now);
      if (fail) {
        ctx.addIssue({
          code: "custom",
          path: [field.id],
          message: message(form.texts, field.id, fail.rule, fail.limit),
        });
      }
    }
  });
}
```

## Rules and error keys

`failure` returns the first rule a visible field breaks. Its rule names are the error keys that the builder uses (`required`, `minLength`, `maxLength`, `pattern`, `email`, `phone`, `url`, `min`, `max`, `wholeNumber`, `minDate`, `maxDate`, `minTime`, `maxTime`, `minItems`, `maxItems`).

```ts title="examples/form-builder-next/src/lib/form-builder/zod.ts (trimmed)"
function failure(f: FormField, value: unknown, now: Date): { rule: string; limit?: string | number } | undefined {
  const v = f.validations ?? {};
  if (f.type === "hidden") return undefined;
  const flag = f.type === "yesNo" || f.type === "consent";
  if (flag ? value !== true : isEmpty(value)) return f.required ? { rule: "required" } : undefined;
  // ...
  switch (f.type) {
    case "email":
      return EMAIL.test(s) ? undefined : { rule: "email" }; // the same pattern as the builder's check
    case "phone": {
      const digits = s.replace(/^\+/, ""); // an optional leading plus
      const ok = /^[0-9]+$/.test(digits) && digits.length >= (v.minDigits ?? 10) && digits.length <= (v.maxDigits ?? 15);
      return ok ? undefined : { rule: "phone" };
    }
    case "date": {
      const today = new Date(now.getTime() - now.getTimezoneOffset() * 6e4).toISOString().slice(0, 10); // local date
      const min = v.minDate === "today" ? today : v.minDate;
      if (min && s < min) return { rule: "minDate", limit: min };
      // ...
    }
    // ...
  }
}
```

- An empty optional field passes. An empty Yes/No or Consent field counts as "no", so it fails only when it's required.
- Short text patterns (`letters`, `numbers`, `lettersNumbers`, or a custom expression) are applied with the `u` flag. A custom expression that doesn't compile is skipped, since the builder reports it.
- `today` in a date rule is the local date where the check runs: the visitor's, in the browser.
- Email and web address checks use the same patterns as the builder's Preview, so an answer that passes here passes there.
- Text lengths count characters as people see them, so an emoji counts as one.

## Messages

The message for a failed rule comes from the form's merged texts: the field's own `<fieldId>.errors.<rule>`, then `form.errors.<rule>`. `{limit}` is replaced with the limit.

```ts title="examples/form-builder-next/src/lib/form-builder/texts.ts"
export function message(texts: Texts, fieldId: string, rule: string, limit?: string | number): string {
  const found = [`${fieldId}.errors.${rule}`, `form.errors.${rule}`]
    .map((k) => texts[k])
    .find((v) => typeof v === "string");
  const text = (found as string | undefined) ?? rule;
  return limit === undefined ? text : text.replaceAll("{limit}", String(limit));
}
```

If neither key exists, the message is the rule name. A form made in the app has the form-wide messages in its default locale.

## JSON Schema instead

If you validate with another library, the **Developer** tab of each form shows a JSON Schema (draft-07) and a TypeScript type for its submission. See [Data format](https://contentful.geeconglobal.com/apps/form-builder/docs/data-format).
