@railway-ts/use-form 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ # Getting Started
2
+
3
+ A guided walkthrough. Each step introduces one concept, building to a complete form by the end.
4
+
5
+ ---
6
+
7
+ ## Step 1: Your First Form
8
+
9
+ Every `useForm` starts with a **schema** -- an object that describes what your form data looks like and how to validate it. The schema is the single source of truth: it defines both the validation rules and the TypeScript types at the same time.
10
+
11
+ ```tsx
12
+ import { useForm } from '@railway-ts/use-form';
13
+ import {
14
+ object,
15
+ string,
16
+ required,
17
+ chain,
18
+ nonEmpty,
19
+ type InferSchemaType,
20
+ } from '@railway-ts/pipelines/schema';
21
+
22
+ // 1. Define a schema
23
+ const loginSchema = object({
24
+ email: required(chain(string(), nonEmpty('Email is required'))),
25
+ password: required(chain(string(), nonEmpty('Password is required'))),
26
+ });
27
+
28
+ // 2. Derive the TypeScript type from the schema -- no separate interface needed
29
+ type LoginForm = InferSchemaType<typeof loginSchema>;
30
+ // { email: string; password: string }
31
+ ```
32
+
33
+ Here's what's happening:
34
+
35
+ - `object({...})` declares the shape -- each key is a field
36
+ - `required(...)` marks a field as mandatory
37
+ - `string()` checks that the value is a string
38
+ - `chain(...)` sequences validators left to right -- each one feeds into the next
39
+ - `nonEmpty('...')` ensures the string isn't blank, with a custom error message
40
+ - `InferSchemaType` extracts the TypeScript type so you never write it by hand
41
+
42
+ Now pass the schema and initial values to `useForm`:
43
+
44
+ ```tsx
45
+ function LoginForm() {
46
+ const form = useForm<LoginForm>(loginSchema, {
47
+ initialValues: { email: '', password: '' },
48
+ onSubmit: async (values) => {
49
+ // values is typed as { email: string; password: string }
50
+ console.log('Login:', values);
51
+ },
52
+ });
53
+
54
+ return (
55
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
56
+ <input type="email" placeholder="Email" />
57
+ <input type="password" placeholder="Password" />
58
+ <button type="submit">Log In</button>
59
+ </form>
60
+ );
61
+ }
62
+ ```
63
+
64
+ The form validates and submits, but the inputs aren't wired up yet. That's the next step.
65
+
66
+ > **Want the full theory on schemas, Result types, and pipelines?** See the [@railway-ts/pipelines Getting Started](https://github.com/sakobu/railway-ts-pipelines/blob/main/docs/GETTING_STARTED.md). You don't need to read it first -- we'll explain enough here to follow along.
67
+
68
+ ---
69
+
70
+ ## Step 2: Field Bindings
71
+
72
+ `getFieldProps` returns everything a native HTML input needs -- `id`, `name`, `value`, `onChange`, `onBlur` -- in one object. Spread it onto the element and you're done:
73
+
74
+ ```tsx
75
+ function LoginForm() {
76
+ const form = useForm<LoginForm>(loginSchema, {
77
+ initialValues: { email: '', password: '' },
78
+ onSubmit: async (values) => {
79
+ console.log('Login:', values);
80
+ },
81
+ });
82
+
83
+ return (
84
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
85
+ <div>
86
+ <label htmlFor="field-email">Email</label>
87
+ <input type="email" {...form.getFieldProps('email')} />
88
+ {form.touched.email && form.errors.email && (
89
+ <span className="error">{form.errors.email}</span>
90
+ )}
91
+ </div>
92
+
93
+ <div>
94
+ <label htmlFor="field-password">Password</label>
95
+ <input type="password" {...form.getFieldProps('password')} />
96
+ {form.touched.password && form.errors.password && (
97
+ <span className="error">{form.errors.password}</span>
98
+ )}
99
+ </div>
100
+
101
+ <button type="submit" disabled={form.isSubmitting}>
102
+ {form.isSubmitting ? 'Logging in...' : 'Log In'}
103
+ </button>
104
+ </form>
105
+ );
106
+ }
107
+ ```
108
+
109
+ The error display pattern is `touched && errors` -- show the error only after the user has interacted with the field. This prevents a wall of errors before they've typed anything.
110
+
111
+ There are specialized binding helpers for other input types:
112
+
113
+ | Input Type | Helper | Returns |
114
+ | ---------------------- | ------------------------------------------- | ------------------------------------------------------ |
115
+ | Text, email, textarea | `getFieldProps(field)` | `id`, `name`, `value`, `onChange`, `onBlur` |
116
+ | Select | `getSelectFieldProps(field)` | `id`, `name`, `value`, `onChange`, `onBlur` |
117
+ | Checkbox (boolean) | `getCheckboxProps(field)` | `id`, `name`, `checked`, `onChange`, `onBlur` |
118
+ | Switch (toggle) | `getSwitchProps(field)` | `id`, `name`, `checked`, `onChange`, `onBlur` |
119
+ | Slider (range) | `getSliderProps(field)` | `id`, `name`, `type`, `value`, `onChange`, `onBlur` |
120
+ | File | `getFileFieldProps(field)` | `id`, `name`, `onChange`, `onBlur` |
121
+ | Checkbox group (array) | `getCheckboxGroupOptionProps(field, value)` | `id`, `name`, `value`, `checked`, `onChange`, `onBlur` |
122
+ | Radio group | `getRadioGroupOptionProps(field, value)` | `id`, `name`, `value`, `checked`, `onChange`, `onBlur` |
123
+
124
+ All of them generate a stable `id` (e.g., `field-email`) that matches `<label htmlFor>` automatically.
125
+
126
+ ---
127
+
128
+ ## Step 3: Validation
129
+
130
+ Validators compose with `chain` -- each step runs left to right, and all errors are collected in a single pass:
131
+
132
+ ```typescript
133
+ import {
134
+ object,
135
+ string,
136
+ required,
137
+ chain,
138
+ nonEmpty,
139
+ email,
140
+ minLength,
141
+ type InferSchemaType,
142
+ } from '@railway-ts/pipelines/schema';
143
+
144
+ const signupSchema = object({
145
+ email: required(
146
+ chain(
147
+ string(),
148
+ nonEmpty('Email is required'),
149
+ email('Must be a valid email')
150
+ )
151
+ ),
152
+ password: required(
153
+ chain(
154
+ string(),
155
+ nonEmpty('Password is required'),
156
+ minLength(8, 'Must be at least 8 characters')
157
+ )
158
+ ),
159
+ });
160
+ ```
161
+
162
+ If a user submits with an empty email and a 3-character password, they see both errors at once -- not one at a time. This is the "railway" approach: each field travels its own track, and errors accumulate across all fields rather than short-circuiting at the first failure.
163
+
164
+ Under the hood, validators return a `Result` -- either `Ok` with the validated value, or `Err` with an array of errors. You don't need to work with `Result` directly for basic forms (the hook handles it), but it's there when you want more control. See [Pattern-Matching Submit Results](./RECIPES.md#pattern-matching-submit-results) for an example.
165
+
166
+ > **Deep dive:** The [@railway-ts/pipelines Getting Started](https://github.com/sakobu/railway-ts-pipelines/blob/main/docs/GETTING_STARTED.md) explains `Result`, `chain`, `pipe`, and the full validation model.
167
+
168
+ ---
169
+
170
+ ## Step 4: Validation Modes
171
+
172
+ By default, validation runs on every change. That's great for short forms, but intrusive for long ones. The `validationMode` option controls when validation fires:
173
+
174
+ | Mode | Validates on | Marks touched on | Best for |
175
+ | ---------------- | --------------- | ------------------- | ----------------------------------- |
176
+ | `live` (default) | Change and blur | Change | Short forms, immediate feedback |
177
+ | `blur` | Blur only | Blur | Longer forms, less intrusive typing |
178
+ | `mount` | Mount (once) | Mount (all fields) | Editing existing records |
179
+ | `submit` | Submit only | Submit (all fields) | Simple forms, minimal interruption |
180
+
181
+ ```typescript
182
+ // Validate only when a field loses focus
183
+ const form = useForm(validator, {
184
+ initialValues: {
185
+ /* ... */
186
+ },
187
+ validationMode: 'blur',
188
+ });
189
+ ```
190
+
191
+ ```typescript
192
+ // Pre-fill a form for editing and show all errors immediately
193
+ const form = useForm(validator, {
194
+ initialValues: existingUser,
195
+ validationMode: 'mount',
196
+ });
197
+ ```
198
+
199
+ ```typescript
200
+ // Don't bother the user until they submit
201
+ const form = useForm(validator, {
202
+ initialValues: {
203
+ /* ... */
204
+ },
205
+ validationMode: 'submit',
206
+ });
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Step 5: Submission and Server Errors
212
+
213
+ When the user submits, `handleSubmit` validates the form, marks all fields as touched, and calls your `onSubmit` callback if validation passes. Server errors are set separately and display through the same `form.errors` object:
214
+
215
+ ```tsx
216
+ function RegistrationForm() {
217
+ const form = useForm<RegistrationForm>(registrationSchema, {
218
+ initialValues: { username: '', email: '', password: '' },
219
+ onSubmit: async (values) => {
220
+ const response = await fetch('/api/register', {
221
+ method: 'POST',
222
+ headers: { 'Content-Type': 'application/json' },
223
+ body: JSON.stringify(values),
224
+ });
225
+
226
+ if (!response.ok) {
227
+ const errors = await response.json();
228
+ // { username: "Username already taken", email: "Email in use" }
229
+ form.setServerErrors(errors);
230
+ return;
231
+ }
232
+
233
+ window.location.href = '/dashboard';
234
+ },
235
+ });
236
+
237
+ return (
238
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
239
+ <input {...form.getFieldProps('username')} />
240
+ {form.touched.username && form.errors.username && (
241
+ <span>{form.errors.username}</span>
242
+ )}
243
+
244
+ <input type="email" {...form.getFieldProps('email')} />
245
+ {form.touched.email && form.errors.email && (
246
+ <span>{form.errors.email}</span>
247
+ )}
248
+
249
+ <input type="password" {...form.getFieldProps('password')} />
250
+ {form.touched.password && form.errors.password && (
251
+ <span>{form.errors.password}</span>
252
+ )}
253
+
254
+ <button type="submit" disabled={form.isSubmitting}>
255
+ {form.isSubmitting ? 'Registering...' : 'Register'}
256
+ </button>
257
+ </form>
258
+ );
259
+ }
260
+ ```
261
+
262
+ Three things to know about server errors:
263
+
264
+ 1. **They auto-clear** -- when the user edits a field, its server error disappears
265
+ 2. **They win** -- if a field has both a client error and a server error, the server error is displayed (server > fieldValidator > client)
266
+ 3. **Form-level errors** -- use `ROOT_ERROR_KEY` (from `@railway-ts/pipelines/schema`) for errors not tied to a specific field (e.g., network errors, rate limiting)
267
+
268
+ `handleSubmit` accepts an optional form event. When passed, it calls `e.preventDefault()` automatically. You can also call `handleSubmit()` without an event -- useful for programmatic submission (e.g., after a "Next" button in a wizard).
269
+
270
+ `handleSubmit` also returns a `Result`, so you can pattern-match on the outcome instead of using `onSubmit`. See [Recipes](./RECIPES.md#pattern-matching-submit-results) for that pattern.
271
+
272
+ > **React 19 note:** React 19 form actions expect `onSubmit` to not return a Promise. Use `(e) => void form.handleSubmit(e)` to satisfy the type checker.
273
+
274
+ ---
275
+
276
+ ## Step 6: Nested Objects
277
+
278
+ Use dot notation everywhere -- field props, errors, touched state:
279
+
280
+ ```tsx
281
+ const profileSchema = object({
282
+ name: required(string()),
283
+ address: required(
284
+ object({
285
+ street: required(string()),
286
+ city: required(chain(string(), nonEmpty('City is required'))),
287
+ zip: required(chain(string(), nonEmpty('ZIP is required'))),
288
+ })
289
+ ),
290
+ });
291
+
292
+ type Profile = InferSchemaType<typeof profileSchema>;
293
+
294
+ function ProfileForm() {
295
+ const form = useForm<Profile>(profileSchema, {
296
+ initialValues: {
297
+ name: '',
298
+ address: { street: '', city: '', zip: '' },
299
+ },
300
+ });
301
+
302
+ return (
303
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
304
+ <input {...form.getFieldProps('name')} placeholder="Name" />
305
+
306
+ <fieldset>
307
+ <legend>Address</legend>
308
+ <input {...form.getFieldProps('address.street')} placeholder="Street" />
309
+ <input {...form.getFieldProps('address.city')} placeholder="City" />
310
+ {form.touched['address.city'] && form.errors['address.city'] && (
311
+ <span>{form.errors['address.city']}</span>
312
+ )}
313
+ <input {...form.getFieldProps('address.zip')} placeholder="ZIP" />
314
+ {form.touched['address.zip'] && form.errors['address.zip'] && (
315
+ <span>{form.errors['address.zip']}</span>
316
+ )}
317
+ </fieldset>
318
+
319
+ <button type="submit">Save</button>
320
+ </form>
321
+ );
322
+ }
323
+ ```
324
+
325
+ The field path autocomplete works through nested objects -- type `'address.'` and your editor suggests `street`, `city`, `zip`.
326
+
327
+ ---
328
+
329
+ ## Step 7: Arrays
330
+
331
+ Use `arrayHelpers` for dynamic lists. It gives you `push`, `remove`, `swap`, `move`, `insert`, `replace`, and its own `getFieldProps` that takes an index:
332
+
333
+ ```tsx
334
+ import {
335
+ object,
336
+ string,
337
+ required,
338
+ email,
339
+ array,
340
+ type InferSchemaType,
341
+ } from '@railway-ts/pipelines/schema';
342
+
343
+ const contactSchema = object({
344
+ name: required(string()),
345
+ email: required(email()),
346
+ });
347
+
348
+ const formSchema = object({
349
+ contacts: array(contactSchema),
350
+ });
351
+
352
+ type ContactsForm = InferSchemaType<typeof formSchema>;
353
+
354
+ function ContactsForm() {
355
+ const form = useForm<ContactsForm>(formSchema, {
356
+ initialValues: { contacts: [{ name: '', email: '' }] },
357
+ });
358
+
359
+ const helpers = form.arrayHelpers('contacts');
360
+
361
+ return (
362
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
363
+ {helpers.values.map((_, index) => (
364
+ <div key={index}>
365
+ <h3>Contact {index + 1}</h3>
366
+
367
+ <input {...helpers.getFieldProps(index, 'name')} placeholder="Name" />
368
+ {form.touched[`contacts.${index}.name`] &&
369
+ form.errors[`contacts.${index}.name`] && (
370
+ <span>{form.errors[`contacts.${index}.name`]}</span>
371
+ )}
372
+
373
+ <input
374
+ {...helpers.getFieldProps(index, 'email')}
375
+ placeholder="Email"
376
+ />
377
+ {form.touched[`contacts.${index}.email`] &&
378
+ form.errors[`contacts.${index}.email`] && (
379
+ <span>{form.errors[`contacts.${index}.email`]}</span>
380
+ )}
381
+
382
+ <button type="button" onClick={() => helpers.remove(index)}>
383
+ Remove
384
+ </button>
385
+ </div>
386
+ ))}
387
+
388
+ <button
389
+ type="button"
390
+ onClick={() => helpers.push({ name: '', email: '' })}
391
+ >
392
+ Add Contact
393
+ </button>
394
+
395
+ <button type="submit">Save All</button>
396
+ </form>
397
+ );
398
+ }
399
+ ```
400
+
401
+ Array helpers provide full type safety -- `helpers.getFieldProps(index, 'name')` autocompletes to the fields of your contact schema.
402
+
403
+ **All array operations:**
404
+
405
+ | Method | What it does |
406
+ | ----------------------------- | ------------------------- |
407
+ | `push(item)` | Add to end |
408
+ | `remove(index)` | Remove by index |
409
+ | `insert(index, item)` | Insert at position |
410
+ | `swap(indexA, indexB)` | Swap two items |
411
+ | `move(from, to)` | Move item to new position |
412
+ | `replace(index, item)` | Replace item at index |
413
+ | `getFieldProps(index, field)` | Get props for item field |
414
+
415
+ ---
416
+
417
+ ## What's Next
418
+
419
+ You now know the core: schemas, field bindings, validation, submission, nesting, and arrays.
420
+
421
+ - **[Recipes](./RECIPES.md)** -- Patterns and techniques: Standard Schema (Zod/Valibot), per-field async validation, cross-field validation, UI library integration, multi-step wizards, and more
422
+ - **[API Reference](./API.md)** -- Complete API documentation