UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

203 lines (154 loc) • 6.19 kB
# Validation > Checking input before submit, and showing the server's validation errors in a form. A validation error is a field name mapped to its messages, wherever it came from: ```ts { title: ['The title must be at least 3 characters.'], body: ['The body is required.'] } ``` `<Form>` shows these under its fields, whether they came from a schema in the browser or from the server. ## Showing errors in a form ```tsx title="src/components/PostForm.tsx" "use client"; import { Form } from '@rsc-kit/core/form'; import { createPost } from '../actions'; export function PostForm() { return ( <Form action={createPost}> {({ error, pending }) => ( <> <input name="title" /> {error('title') && <p className="error">{error('title')}</p>} <textarea name="body" /> {error('body') && <p className="error">{error('body')}</p>} <button disabled={pending}>Create</button> </> )} </Form> ); } ``` There's no `try`/`catch` and no state of your own. A failed submit fills `errors`, and a successful one clears them. ## Checking before submit Pass `<Form>` a schema. Any [Standard Schema](https://standardschema.dev) works - Zod, Valibot, ArkType - with no adapter: ```tsx title="src/components/PostForm.tsx" "use client"; import { z } from 'zod'; import { Form } from '@rsc-kit/core/form'; import { createPost } from '../actions'; const schema = z.object({ title: z.string().min(3, 'Too short'), body: z.string().min(10, 'Too short'), }); export function PostForm() { return ( <Form action={createPost} schema={schema}> {({ error, pending }) => ( <> <input name="title" /> {error('title') && <p className="error">{error('title')}</p>} <textarea name="body" /> {error('body') && <p className="error">{error('body')}</p>} <button disabled={pending}>Create</button> </> )} </Form> ); } ``` When the schema fails, the errors appear the same way and the action is never called. That saves a round trip, and an optimistic update never shows a row the server would refuse. Async schemas are awaited, so a uniqueness check works too. - A nested field is named by its path: `address.city`. - An error that belongs to no field, such as "these must match", is under the empty string `''`. <Aside type="danger" title="The server still has to check"> A schema in the browser is a convenience, not a control. The action is a public endpoint anyone can call without this form, so the server must validate too. Using the same schema on both sides is fine. See [Authorization](/guides/authorization). </Aside> ## Checking with the backend's rules When a backend action describes its input, `<Form>` checks it with no `schema` prop. The backend's rules and messages are the only copy, and the browser shows the same words a submit would: ```tsx <Form action={store}> {({ error }) => ( <> <input name="email" /> {error('email') && <p className="error">{error('email')}</p>} </> )} </Form> ``` The backend writes the input's JSON Schema, with its own messages, under `schemas` in `rsc-host.json`. How: - **Laravel**: a form request's `schema()`, built with `Illuminate\JsonSchema`. See [Checking a form in the browser with JSON Schema](/hosts/laravel/server-actions#checking-a-form-in-the-browser-with-json-schema). - **Go**: `CheckInBrowser`. See [Checking a form in the browser](/hosts/go/server-actions#checking-a-form-in-the-browser). - **Your own backend**: [Describing a form's input](/hosts/your-own-backend/server-actions#describing-a-forms-input). - Nothing is added to the page. Focusing a field loads a small index of the actions that have schemas, and the first check loads that action's schema and a 2.5 KB validator, [json-schema-to-standard](https://www.npmjs.com/package/json-schema-to-standard). Both are cached files, shared by every page. - It works whether the form imports its action or is handed it by a server component. - A blank field the schema doesn't require isn't posted. To the backend's rules a blank optional field is absent, so posted as `""` it would fail a rule the browser passed. - A `schema` prop, when there is one, is used instead. ## Validating in a server action Validate with the same schema in the action, and **return** the failure rather than throwing it: ```ts title="src/actions.ts" 'use server' import { schema } from './schema'; export async function createPost(title: string, body: string) { const parsed = await schema['~standard'].validate({ title, body }); if (parsed.issues) { return { ok: false as const, issues: parsed.issues }; } return { ok: true as const, post: await savePost(parsed.value) }; } ``` Then turn the issues into the error `<Form>` understands with `issuesToErrors`: ```tsx title="src/components/PostForm.tsx" import { ServerValidationError } from '@rsc-kit/core/errors'; import { issuesToErrors } from '@rsc-kit/core/standardSchema'; async function submit(formData: FormData) { const result = await createPost( formData.get('title') as string, formData.get('body') as string, ); if (!result.ok) throw new ServerValidationError('Validation failed', issuesToErrors(result.issues)); return result.post; } ``` `issuesToErrors` is the mapping the browser-side check uses, so field names match whichever side found the error. rsc-kit has no validation rules of its own. Deciding what is invalid is your code's job, or your backend's: a Laravel `FormRequest`'s 422 arrives as the same errors. ## Catching errors outside a form Anywhere else, catch `ServerValidationError`: ```tsx "use client"; import { ServerValidationError } from '@rsc-kit/core/errors'; import { createPost } from '../actions'; try { await createPost(title, body); } catch (error) { if (error instanceof ServerValidationError) { setErrors(error.errors); } } ``` | Member | Type | What it holds | | --- | --- | --- | | `errors` | `Record<string, string[]>` | Field name to messages. | | `message` | `string` | A summary, for when there is nowhere to put field errors. |