Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/doc-form-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@tanstack/cms-ui-react': minor
---

`DocForm` and `useDocForm` validate in the browser. Each field is checked against the collection schema when it loses focus and again on submit, with core's `schemaIssues`: the rules the server's write path runs. A submit that fails them doesn't call `onSubmit`, and `submit()` resolves `false`.

- Messages in `errors` (a save's `fieldErrors`) still replace the form's own.
- Fields that aren't rendered, and fields the session can't write, aren't checked.
- Custom `validate`, `unique`, relation targets, hooks and access stay server-side.
- `validate: false` turns the schema checks off.
- `fieldValidators: { [name]: fn | false }` replaces a field's check. Each function receives `{ value, doc, field, schemaError }`.
- `useDocForm` returns `fieldErrors` and `validatorsFor(name)`, which gives the `validators` for your own `form.Field`.

A field counts as blurred when focus leaves it, not when focus moves between the inputs of one array or group. `FieldInput` keeps its control mounted when an error appears or clears, so the input being typed in isn't replaced.

The admin's edit route gets the checks through `DocForm`. A save they block shows the inline errors and a "Fix the highlighted fields" alert, and sends nothing.
5 changes: 5 additions & 0 deletions .changeset/schema-issues.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/cms-core': minor
---

`schemaIssues(collection, doc)` returns what the server's schema checks report for a document, as `{ path, message }` issues, without saving it. It covers types, `required`, `min`/`max`, formats, options, and `required` on visible conditional fields, after the same derived-field fill as a write. Custom `validate`, relation targets, `unique`, hooks and access stay server-side. The write path runs the same functions, so a form that checks with it before saving agrees with the server.
23 changes: 23 additions & 0 deletions docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,29 @@ const result = schemaFor(post).safeParse({ ...emptyDoc(post), title: 'Hello', ta
if (!result.success) console.log(result.error.issues)
```

### `schemaIssues(collection, doc)`

```ts
function schemaIssues(collection: Collection, doc: Record<string, unknown>): Array<SchemaIssue>
interface SchemaIssue { path: Array<string>; message: string }
```

What a write would report from the schema, without saving. It fills derived fields as a write does, parses with `schemaFor`, and adds `required` on the fields that `showWhen` shows. The write path runs the same functions, so the issues match a save's `VALIDATION_FAILED` details. Custom `validate`, relation targets, `unique`, hooks and access aren't included: only the server runs them. Client-safe; `DocForm` uses it to validate before a save.

```ts validate=type
import { defineCollection, emptyDoc, schemaIssues } from '@tanstack/cms-core'
const post = defineCollection({
name: 'post',
label: 'Posts',
titleField: 'title',
fields: [{ name: 'title', label: 'Title', type: 'text', required: true }],
})
schemaIssues(post, { ...emptyDoc(post), title: '' })
// → [{ path: ['title'], message: 'Title is required' }]
```

### `blocksSchema()`, `aiBlocksSchema()`, `normalizeBlocks(raw)`

```ts
Expand Down
54 changes: 50 additions & 4 deletions docs/api/cms-ui-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,15 +417,61 @@ export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Prom
| `renderers` | `CmsRenderers` | The app-wide renderers module from `defineRenderers({ inputs, fieldTypes })`, passed to every `FieldInput`, nested fields included. Without it, `FieldInput` uses the module bound through `createRoutes(definition, { renderers })`. `useDocForm` takes it too. |
| `access` | `{ session, doc }` | Field-level access: fields the session can't read are left out, and fields it can't write are read-only. `doc` is the stored document, or `null` for the draft. Without `access`, every field is editable; the server still enforces field rules. |
| `disabled` | `boolean` | Renders every field read-only. |
| `errors` | `Record<string, string>` | Messages by field name, shown under each control (for example the `fieldErrors` of a failed save). |
| `validate` | `boolean` | Checks fields against the collection schema on blur and on submit (see [Validation](#validation)). Default `true`. `useDocForm` takes it too. |
| `fieldValidators` | `{ [fieldName]: ((args) => string \| undefined) \| false }` | Per-field checks run instead of the schema check, or `false` to turn a field's checks off. `useDocForm` takes it too. |
| `errors` | `Record<string, string>` | Messages by field name, shown under each control in place of the form's own (for example the `fieldErrors` of a failed save). |
| `changedFields` | `Array<string>` | Field names to highlight, as `FieldInput`'s `changed` does (for example the fields an agent's proposal changes). |
| `store`, `relationSearch` | | Passed to `FieldInput`: relation titles by collection and id, and the relation search backend. |
| `id`, `className`, `aria-label` | | Set on the `<form>`. `aria-label` defaults to the collection's label. |
| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, submit, reset, setValue }`. |
| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, fieldErrors, submit, reset, setValue }`. |
`renderers` and `fieldRenderers` work at different levels. `renderers` is the app's module, keyed by input name (a field's `input`) and by custom field type. `fieldRenderers` is an override for one form, keyed by field type. For each top-level field, `DocForm` uses `fieldRenderers[field.type]` if there is one. Otherwise it renders `FieldInput`, which resolves as usual: the field's named input, then its custom type's input (each from `renderers`, then the bound module), then the built-in control. A `renderers.fieldTypes` input replaces only the control under `FieldInput`'s label and error message, and it can't target built-in types. A `fieldRenderers` entry replaces the whole field, for any type.
Fields hidden by `showWhen` aren't rendered, and their stored values stay in the document. There is no client-side validation yet: put a save's field errors in `errors`.
Fields hidden by `showWhen` aren't rendered, and their stored values stay in the document.
#### Validation
`DocForm` checks each field when it loses focus and again on submit, with the rules the server applies to a write: types, `required`, `min`/`max`, the `slug`, `email`, `url` and `color` formats, select options, and `required` on fields that `showWhen` shows. The checks are `schemaIssues(collection, doc)` from `@tanstack/cms-core`, the functions the server's write path runs, so the form and the server can't disagree about them. A submit that fails them doesn't call `onSubmit`, and `submit()` resolves `false`.
Some rules need the server, so they still surface as a save's errors:
- custom `validate` functions and Standard Schemas;
- `unique`;
- relation targets that must exist;
- `preValidate` hooks;
- access.
Put the save's `fieldErrors` in `errors`. A message in `errors` replaces the form's own for that field.
Fields that aren't rendered (hidden by `showWhen` or by read access) and fields the session can't write aren't checked: the user couldn't fix them.
`validate={false}` turns the schema checks off. `fieldValidators` replaces them for single fields. Each entry gets `{ value, doc, field, schemaError }` and returns a message, or nothing when the value is fine; `false` turns that field's checks off:
```tsx validate=type
import { isSafeRedirectTarget } from '@tanstack/cms-core'
import { DocForm } from '@tanstack/cms-ui-react/primitives'
import type { Doc } from '@tanstack/cms-core'

export function RedirectForm({ redirect, save }: { redirect: Doc; save: (patch: Doc) => Promise<void> }) {
return (
<DocForm
collection="redirect"
defaultValue={redirect}
fieldValidators={{
// Keep the schema's message, and run the field's server rule early.
to: ({ value, schemaError }) =>
schemaError ??
(isSafeRedirectTarget(value) ? undefined : 'Must be a path starting with / or an http(s) URL'),
}}
onSubmit={(patch) => save(patch)}
>
<button type="submit">Save</button>
</DocForm>
)
}
```

When you render `editor.form.Field` yourself instead of `DocForm`, pass `validators={editor.validatorsFor(name)}` to get the same checks.

To keep the form's state in the parent (for example to put the buttons in a header), call `useDocForm` with the same options and pass the result to `DocForm` as `form`:

Expand Down Expand Up @@ -455,7 +501,7 @@ export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publi
}
```

`useDocForm` returns `{ form, collection, values, baseline, patch, dirty, submitting, error, submit, reset, setValue }`. `form` is the TanStack Form instance, for `form.Field` and `form.Subscribe`. `submit(meta?)` resolves `true` when `onSubmit` succeeded. `reset()` goes back to the baseline, and `reset(doc)` loads `doc` and makes it the baseline. `docPatch(baseline, doc)` is the patch computation on its own (also exported from `@tanstack/cms-core`).
`useDocForm` returns `{ form, collection, values, baseline, patch, dirty, submitting, error, fieldErrors, submit, reset, setValue, validatorsFor }`. `form` is the TanStack Form instance, for `form.Field` and `form.Subscribe`. `submit(meta?)` validates the fields, then resolves `true` when `onSubmit` succeeded, and `false` when a field failed its checks or `onSubmit` threw. `fieldErrors` holds the form's own messages by field name. `reset()` goes back to the baseline, and `reset(doc)` loads `doc` and makes it the baseline. `docPatch(baseline, doc)` is the patch computation on its own (also exported from `@tanstack/cms-core`).

#### With the core editor store

Expand Down
5 changes: 4 additions & 1 deletion docs/schema/collections-and-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,8 @@ export const event = defineCollection({

Failures throw a `CmsError` with code `VALIDATION_FAILED` (HTTP 422) and `details: Array<{ path: Array<string>, message: string }>`, which the admin maps back onto the fields.

`schemaIssues(collection, doc)` runs the schema layer without saving, plus `required` on the fields that `showWhen` shows. It returns the same `{ path, message }` issues a write would. The admin's edit form and [`DocForm`](../api/cms-ui-react#validation) run it on blur and before every save, so the user sees schema errors on the fields they can edit before anything is sent. `validate` runs only on the server: a function may use server-only code, and it gets the document's `id`. To check a rule in the browser too, pass it to `DocForm`'s `fieldValidators`.

## Conditional fields

A field can declare `showWhen` to appear only when a *sibling* field matches. The condition is declarative (and serializable), so it works the same in the admin form and on the server:
Expand Down Expand Up @@ -451,7 +453,7 @@ export const invoice = defineCollection({

## Editing documents in your own UI

The admin's edit screen is generated from these definitions, and a bespoke app can generate the same form. `DocForm` from `@tanstack/cms-ui-react/primitives` takes a collection name, renders a control for each field in schema order, and applies the rules above: fields hidden by `showWhen` aren't shown, and with `access` the session's field rules hide or lock fields. The draft lives in a TanStack Form instance. On submit, your handler gets a patch of the fields that changed, and you decide where it goes:
The admin's edit screen is generated from these definitions, and a bespoke app can generate the same form. `DocForm` from `@tanstack/cms-ui-react/primitives` takes a collection name, renders a control for each field in schema order, and applies the rules above: fields hidden by `showWhen` aren't shown, with `access` the session's field rules hide or lock fields, and the schema's checks run on blur and before each submit. The draft lives in a TanStack Form instance. On submit, your handler gets a patch of the fields that changed, and you decide where it goes:

```tsx validate=type
import { DocForm } from '@tanstack/cms-ui-react/primitives'
Expand Down Expand Up @@ -781,6 +783,7 @@ These client-safe helpers from `@tanstack/cms-core` read the registered config:
| `blockTypes()` / `blockTypeMap()` | The block palette as an array / keyed by `type` |
| `schemaFor(collection)` | Zod object for a full document, including system metadata |
| `scalarSchemaFor(collection)` | Zod object without `blocks` fields (for AI structured output) |
| `schemaIssues(collection, doc)` | The `{ path, message }` issues a write would report from the schema (see [Validation](#validation)) |
| `emptyDoc(collection)` / `emptyBlock(type)` / `emptyArrayItem(field)` | New values with every field defaulted |
| `fillDerivedFields(collection, doc)` | Fills empty `slug` fields from their source |
| `slugify(text, { nested? })` | Lowercase kebab-case (`"Héllo, World!"` → `"hello-world"`); with `nested`, per `/` segment |
Expand Down
49 changes: 49 additions & 0 deletions examples/blog/e2e/editor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,55 @@ test('validation errors appear next to the field', async ({
)
})

test('a save the schema rejects stays in the browser until it is fixed', async ({
page,
context,
}) => {
await signInAs(context, 'admin')
const id = 'e2e-client-check'
const created = await page.request.post('/api/cms/v1/ops/createDoc', {
data: {
collection: 'redirect',
id,
doc: { from: '/e2e-client', to: '/post/hello-world', permanent: true },
},
})
expect(created.status()).toBe(200)

await open(page, `/edit/redirect/${id}`)
const sent: Array<string> = []
page.on('request', (request) => {
if (request.method() === 'POST' && request.postData()?.includes(id)) {
sent.push(request.url())
}
})
const to = page.getByRole('textbox', { name: /^To \(path or URL\)/ })
const error = page.locator('[data-field-error="to"]')

await to.fill('')
await to.blur()
await expect(error).toHaveText('To (path or URL) is required')

await page.getByRole('button', { name: SAVE }).click()
await expect(page.getByRole('alert')).toContainText(
'Fix the highlighted fields',
)
await expect(error).toHaveText('To (path or URL) is required')
expect(sent).toEqual([])
expect((await getDoc(page.request, 'redirect', id)).to).toBe(
'/post/hello-world',
)

await to.fill('/post/fixed')
await to.blur()
await expect(error).toHaveCount(0)
await expect(page.getByRole('alert')).toHaveCount(0)
await page.getByRole('button', { name: SAVE }).click()
await expect(page.getByText(/(Saved|Published) ✓/).first()).toBeVisible()
expect(sent.length).toBeGreaterThan(0)
expect((await getDoc(page.request, 'redirect', id)).to).toBe('/post/fixed')
})

test('scheduling stores the local time as UTC', async ({ page, context }) => {
await signInAs(context, 'admin')
await createDocument(page, 'post', 'E2E scheduled')
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,11 @@ export type {
CreateDocEditorOptions,
} from './lib/doc-editor'

// The schema's document checks (client-safe): the write path runs them, and
// so can a form before it saves.
export { schemaIssues } from './lib/validation'
export type { SchemaIssue } from './lib/validation'

// Lightweight, framework-agnostic feature flags (client-safe). Resolve on the
// server from the request session, ship the booleans, read them via the store.
export { flagEnabled, resolveFlags, createFlagsStore } from './flags'
Expand Down
130 changes: 130 additions & 0 deletions packages/core/src/lib/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* The document checks the schema alone decides. The server's write path runs
* them on every write, and form validation in the browser runs the same
* functions, so the two can't disagree.
*/
import { contentLocales } from '../config'
import { isLocalizedValue, primaryLocaleValue } from '../i18n'
import {
blockTypeMap,
fillDerivedFields,
isFieldVisible,
schemaFor,
} from '../schema'
import type { Collection, Doc, Field, JsonValue } from '../schema'

/** A failed check: the value's path from the document root, and why. */
export interface SchemaIssue {
path: Array<string>
message: string
}

/** A field's value somewhere in a document. */
export interface FieldValueVisit {
field: Field
value: JsonValue | undefined
path: Array<string>
}

/** Whether a value counts as "empty" for a `required` check. */
export function isEmptyFieldValue(v: JsonValue | undefined): boolean {
if (v === undefined || v === null || v === '') return true
if (Array.isArray(v)) return v.length === 0
return false
}

/**
* Every field value a document shows, at any depth (groups, array items,
* blocks), parents before their sub-fields. A field hidden by `showWhen` is
* skipped with everything under it. A localized value is its default
* locale's entry: a missing translation falls back on read.
*/
export function visibleFieldValues(
fields: ReadonlyArray<Field>,
doc: Record<string, unknown> | undefined,
): Array<FieldValueVisit> {
const out: Array<FieldValueVisit> = []
const walk = (
list: ReadonlyArray<Field>,
value: Record<string, unknown> | undefined,
path: Array<string>,
): void => {
for (const f of list) {
if (f.showWhen && !isFieldVisible(f, value as Doc | undefined)) continue
let v = value?.[f.name] as JsonValue | undefined
const at = [...path, f.name]
if (f.localized && isLocalizedValue(v)) {
v = primaryLocaleValue(v, contentLocales()?.defaultLocale ?? 'en') as
| JsonValue
| undefined
}
out.push({ field: f, value: v, path: at })
if (f.type === 'group' && f.fields && v && typeof v === 'object') {
walk(f.fields, v as Record<string, unknown>, at)
}
if (f.type === 'array' && f.fields && Array.isArray(v)) {
for (const [i, item] of v.entries()) {
walk(f.fields, item as Record<string, unknown>, [...at, String(i)])
}
}
if (f.type === 'blocks' && Array.isArray(v)) {
const types = blockTypeMap()
for (const [i, block] of v.entries()) {
if (!block || typeof block !== 'object' || Array.isArray(block))
continue
const b = block as Record<string, unknown>
const typeName =
typeof b._type === 'string'
? b._type
: typeof b.type === 'string'
? b.type
: undefined
const bt = typeName ? types[typeName] : undefined
if (bt) walk(bt.fields, b, [...at, String(i)])
}
}
}
}
walk(fields, doc, [])
return out
}

/**
* `required` on a visible conditional field. The Zod schema relaxes it,
* because only the sibling values decide whether the field is shown.
*/
export function conditionalRequiredIssue(
visit: FieldValueVisit,
): SchemaIssue | undefined {
const { field, value, path } = visit
if (!field.showWhen || field.required !== true) return undefined
if (!isEmptyFieldValue(value)) return undefined
return { path, message: `${field.label} is required` }
}

/**
* What the server's schema checks report for a document: types, `required`,
* `min`/`max`, formats (slug, email, url, color), options, and `required` on
* visible conditional fields, after the same derived-field fill (a slug from
* its source field). The rules only the server can run aren't here: custom
* `validate`, relation targets, `unique`, hooks, and access.
*/
export function schemaIssues(
collection: Collection,
doc: Record<string, unknown>,
): Array<SchemaIssue> {
const filled = fillDerivedFields(collection, doc)
const parsed = schemaFor(collection).safeParse(filled)
const issues: Array<SchemaIssue> = parsed.success
? []
: parsed.error.issues.map((i) => ({
path: i.path.map(String),
message: i.message,
}))
const checked = parsed.success ? (parsed.data as Doc) : filled
for (const visit of visibleFieldValues(collection.fields, checked)) {
const issue = conditionalRequiredIssue(visit)
if (issue) issues.push(issue)
}
return issues
}
Loading
Loading