# El Form — Full Reference for LLMs El Form is a TypeScript-first, schema-agnostic React form library. Two APIs cover the full range from "generate a form for me" to "give me total control": - **AutoForm** — render a complete, validated, styled form straight from a schema. - **useForm** — a hook for custom React forms with register, handleSubmit and formState. Validation is pluggable: Zod (v3 or v4), Yup, Valibot, a custom function, or none. This document is self-contained: an agent can read it and use El Form correctly without fetching anything else. -------------------------------------------------------------------------------- ## Editing TanStack Query records (local development package) The optional `el-form-react-query` workspace package exports `QueryForm`. Render it inside a TanStack Query v5 `QueryClientProvider`. Pass `query` (queryKey and a queryFn that fetches the full record), `schema`, `toValues(record)` and `save(parsedOutput)`. Return the saved full record from save. Render the registered inputs inside a native form with the render prop's handleSubmit. Show mutation.error to support retry. The local guide at /docs/guides/react-query includes a working reservation editor. ## Installation ```bash # Everything (hooks + components + styles) — recommended npm install el-form-react # Just the hooks (custom forms) npm install el-form-react-hooks # Just AutoForm + components npm install el-form-react-components # Framework-agnostic validation engine only npm install el-form-core ``` Validation libraries are optional — install only what you use: ```bash npm install zod # recommended (v3 and v4 both supported) npm install yup npm install valibot ``` The core React packages support React 16.8+. The generated useForm component uses React.useId and requires React 18+, as does the optional React Query adapter. -------------------------------------------------------------------------------- ## Packages | Package | Exports | Use when | | -------------------------- | ---------------------------------------- | -------- | | `el-form-react` | re-exports hooks + components + styles | most apps | | `el-form-react-hooks` | `useForm`, `FormProvider`, `useFormContext`, `useFormSelector`, `useField`, `useWatch`, `useFieldArray`, `shallowEqual` | custom forms | | `el-form-react-components` | `AutoForm`, field components, `styles.css` | schema-driven forms | | `el-form-core` | validation engine + utilities | other frameworks / advanced | -------------------------------------------------------------------------------- ## AutoForm — zero boilerplate ```tsx import { AutoForm } from "el-form-react-components"; import "el-form-react-components/styles.css"; // optional zero-config styling import { z } from "zod"; const schema = z.object({ name: z.string().min(1, "Name is required"), email: z.string().email("Invalid email"), message: z.string().min(10, "Message too short"), }); export function ContactForm({ onSubmit }: { onSubmit: (data: z.output) => void }) { return ; } ``` ### Customizing fields, layout, and async validation ```tsx ``` Common field config keys: `name`, `type` ("text" | "email" | "password" | "number" | "textarea" | "select" | ...), `label`, `placeholder`, `colSpan`, `required`, and `options` (for selects, use objects like { label: "Member", value: "member" }). Numeric and length constraints belong in the schema. ### Custom error component ```tsx import type { AutoFormErrorProps } from "el-form-react-components"; const ErrorList: React.FC = ({ errors, touched }) => { const entries = Object.entries(errors).filter(([f]) => touched[f]); if (entries.length === 0) return null; return (
    {entries.map(([field, error]) => (
  • {field}: {error}
  • ))}
); }; ; ``` -------------------------------------------------------------------------------- ## useForm — full control ```tsx import { useForm } from "el-form-react-hooks"; import { z } from "zod"; const schema = z.object({ email: z.string().email(), password: z.string().min(8), }); export function LoginForm({ signIn }: { signIn: (data: z.output) => Promise }) { const { register, handleSubmit, formState } = useForm({ validators: { onChange: schema }, defaultValues: { email: "", password: "" }, }); return (
{formState.errors.email && {formState.errors.email}} {formState.errors.password && {formState.errors.password}}
); } ``` `useForm` returns (most-used): `register`, `handleSubmit`, `formState` (`values`, `errors`, `touched`, `isDirty`, `isSubmitting`, `isValid`, `isValidating`, `isSubmitted`, `isSubmitSuccessful`, `submitCount`, `dirtyFields`), `watch`, `setError`, `clearErrors`, `reset`, `setValue`. Each `errors[field]` is a plain string (no `.message`). `isSubmitted`/`isSubmitSuccessful`/`submitCount` track submit attempts and are reset by `reset()`. `isValidating` is `true` while any async validation (onChange/onBlur/submit/`trigger()` async validator) is in flight, else `false`; reset by `reset()`. `dirtyFields` is a reactive, flat, path-keyed map of dirty fields (e.g. `{ "profile.name": true }`) — the reactive twin of `getDirtyFields()` (keys are path strings, not `keyof T`); reset by `reset()`. There is no `defaultValues` or `isLoading` on `formState` — per-field dirty/touched maps are also available as the `getDirtyFields()` / `getTouchedFields()` methods. Validation triggers are configured per event: ```tsx useForm({ validators: { onChange: schema } }); // validate on change useForm({ validators: { onBlur: schema } }); // validate on blur useForm({ validators: { onSubmit: schema } }); // validate on submit ``` Validation timing options (RHF parity): ```tsx // mode: when a field is first validated useForm({ mode: "onChange" }); // validate every change useForm({ mode: "onBlur" }); // validate on blur useForm({ mode: "onTouched" }); // validate on first blur, then every change once touched useForm({ mode: "onSubmit" }); // validate only on submit (default) useForm({ mode: "all" }); // validate on change and blur // reValidateMode (opt-in; default undefined = unchanged): after the form has been // submitted once, pin post-submit re-validation to a single event. useForm({ validators: { onChange: schema }, reValidateMode: "onBlur" }); // Nuance: register's onChange eagerly CLEARS a field's error before the // reValidateMode gate, so with reValidateMode: "onBlur" a post-submit keystroke // visibly clears the error immediately and a later blur re-adds it if still invalid. ``` -------------------------------------------------------------------------------- ## Validation approaches ```tsx // Zod (recommended) const form = useForm({ validators: { onChange: zodSchema } }); // Yup import * as yup from "yup"; const yupSchema = yup.object({ name: yup.string().required() }); const form = useForm({ validators: { onChange: yupSchema } }); // Valibot import * as v from "valibot"; const valibotSchema = v.object({ name: v.pipe(v.string(), v.minLength(1)) }); const form = useForm({ validators: { onChange: valibotSchema } }); // Custom function — return a message string (or undefined when valid) const form = useForm({ validators: { onSubmit: ({ value }: { value: { email: string } }) => value.email.includes("@") ? undefined : { fields: { email: "Invalid email" } }, }, }); // No validation — just state management const form = useForm({ defaultValues: { email: "" } }); ``` -------------------------------------------------------------------------------- ## Error handling ```tsx const { setError, clearErrors } = useForm({ defaultValues: { email: "" } }); setError("email", "This email is already taken"); clearErrors("email"); clearErrors(); ``` -------------------------------------------------------------------------------- ## Reusable field components ```tsx import { FormProvider, useForm, useFormContext } from "el-form-react-hooks"; function EmailField() { const { form } = useFormContext<{ email: string }>(); return ; } function App() { const form = useForm({ defaultValues: { email: "" } }); return ; } ``` Use a separate prop-based field when the component should work without a provider. Inside a provider, useField and useFormSelector subscribe to reactive changes. -------------------------------------------------------------------------------- ## Reactive hooks (inside ``) `useWatch` — reactively subscribe to value(s) by path; a reactive mirror of `form.watch()` built on the selector store, so each watcher re-renders in isolation. Returns **values only** (use `useField` for `value + error + touched`, or `useFormSelector` for an arbitrary derived slice). Must be used within a ``. ```tsx import { useWatch } from "el-form-react-hooks"; const all = useWatch(); // Partial const email = useWatch("email"); // string const pair = useWatch(["a", "b"]); // { a, b } ``` `useFieldArray` — dynamic array fields. Returns a `fields` array where each row has a stable `id` (use as the React `key`) plus `append`, `prepend`, `insert`, `remove`, `move`, `swap`, `update`, and `replace`. `name` is restricted to array-valued paths; item types are inferred. Works in `FormProvider` (re-renders only when its array changes) or with a `form` prop. ```tsx import { useFieldArray } from "el-form-react-hooks"; const { fields, append, remove } = useFieldArray({ name: "items" }); ``` -------------------------------------------------------------------------------- ## Submit repeated order lines The MCP scaffold takes flat field descriptions. For repeatable rows request the field-arrays topic and use useFieldArray with a custom form. Give React the stable field.id and use the current index for the input name, such as lines.0.quantity. A text input can retain "003" while useForm({ schema }) submits the parsed number 3. The local order editor exercises adding, moving, removing and correcting a line. https://elform.dev/playground?example=order-lines -------------------------------------------------------------------------------- ## Reactive external values (props / server data) `useForm({ values })` re-syncs the form whenever the `values` object's content changes (deep-compared, so a new-object/same-content render is a no-op — no memoization needed). It takes precedence over `defaultValues` for the initial state. Pair with `keepDirtyValues: true` to keep fields the user is mid-editing while untouched fields sync. This is the el-form equivalent of React Hook Form's `values` prop (+ `resetOptions: { keepDirtyValues: true }`) and Formik's `enableReinitialize`. ```tsx useForm({ values: serverData, keepDirtyValues: true }); ``` Notes: `values` replaces the **whole** value object (full shape, not a partial patch); `isDirty` is measured against `defaultValues`, not the latest `values`; don't put `File`/`Blob` in reactive `values` (deep-compare can't tell two files apart). -------------------------------------------------------------------------------- ## Schema transforms On the P8 implementation, form state uses the schema's input type. Passing a schema to useForm or AutoForm makes its parsed output available on valid submission. ```tsx const schema = z.object({ seats: z.string().regex(/^\d+$/).transform(Number) }); const form = useForm({ schema, defaultValues: { seats: "3" } }); const save = form.handleSubmit(({ seats }) => { seats.toFixed(0); // number }); ``` Use form.watch("seats") to read the editable string. The success branch of await form.submitAsync() contains the parsed output in data. A failed parse yields field errors and blocks the success callback. Async transforms are awaited. For Yup or Valibot, pass an explicit Standard Schema v1 parser to useForm({ schema }) to submit its parsed output. Supplying those providers under validators checks the editable input. AutoForm uses Zod to generate fields. -------------------------------------------------------------------------------- ## Build and verify a form with MCP A stdio client can start the published server with npx -y el-form-mcp. For this checkout's development tools, build with pnpm --filter el-form-mcp build and start node /absolute/path/to/el-form/packages/el-form-mcp/dist/index.js. Call tools/list to see what the installed server offers. - el_form_overview, el_form_list_topics, el_form_get_topic and el_form_search serve the bundled API reference. - el_form_scaffold_form accepts fields, an optional api ("autoform" or "useform"), and an optional AutoForm theme. The local named presets are default, minimal, dark, card, inline and dense. Reuse a design in React with a typed AutoFormDesign object containing theme, classNames and componentMap. It returns structuredContent.code and structuredContent.schema. The generated module exports GeneratedForm and schema. Pass an onSubmit callback to GeneratedForm. Import React 18+ for the generated custom controls. Set `includeTest: true` on the scaffold call for a runnable Vitest/Testing Library test and replayable samples. Save `code` as `GeneratedForm.tsx` and `verification.testSource` as `GeneratedForm.test.tsx` together. - el_form_validate_schema accepts {schema, sample?} and returns {valid, stage, issues}. A sample may be any JSON value, including null. Omit sample to check the schema only. - el_form_explain_validation_error accepts {errors} for El Form's flat strings or {issues} for a structured issue list. Each returned issue has path, code, message and suggestion. - The el_form_build_and_verify prompt accepts {task} and walks through generation, verification and repair. Example scaffold request: ```json {"api":"autoform","theme":"dark","fields":[{"name":"email","type":"email"},{"name":"role","type":"select","options":["owner","member"]}]} ``` Check the returned schema with {"email":"sam@example.org","role":"viewer"}. Look for valid=false and an issue at ["role"]. Replace viewer with member and repeat. Then compile the generated TSX in the consumer, render it and assert the actual onSubmit payload. Custom transforms and arbitrary business rules need application tests. Guide: https://elform.dev/docs/guides/ai-agents -------------------------------------------------------------------------------- ## Links - Docs: https://elform.dev/docs/intro - Index for LLMs: https://elform.dev/llms.txt - GitHub: https://github.com/colorpulse6/el-form - npm: https://www.npmjs.com/package/el-form-react - MCP server: `npx el-form-mcp` Bundled documentation is available to MCP resource pickers. List resources and read el-form://reference/schema-transforms for the schema input/output guide, or call el_form_get_topic with schema-transforms.