@railway-ts/use-form 0.1.14 → 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,1981 @@
1
+ # Recipes
2
+
3
+ Patterns and techniques. Each recipe is self-contained.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [CRUD Form with Server Errors](#crud-form-with-server-errors)
10
+ 2. [Nested Objects](#nested-objects)
11
+ 3. [Dynamic Arrays](#dynamic-arrays)
12
+ 4. [Checkbox and Radio Groups](#checkbox-and-radio-groups)
13
+ 5. [File Uploads](#file-uploads)
14
+ 6. [Auto-Submit and Debounced Search](#auto-submit-and-debounced-search)
15
+ 7. [Multi-Step Wizard](#multi-step-wizard)
16
+ 8. [Dependent Fields / Cross-Field Validation](#dependent-fields--cross-field-validation)
17
+ 9. [Conditional Validation](#conditional-validation)
18
+ 10. [Discriminated Unions](#discriminated-unions)
19
+ 11. [Custom Validators](#custom-validators)
20
+ 12. [Programmatic Field Updates](#programmatic-field-updates)
21
+ 13. [Syncing Values to External State](#syncing-values-to-external-state)
22
+ 14. [Reacting to Individual Field Changes](#reacting-to-individual-field-changes)
23
+ 15. [submitCount Patterns](#submitcount-patterns)
24
+ 16. [Understanding Error Priority](#understanding-error-priority)
25
+ 17. [Standard Schema: Bring Your Own Validator](#standard-schema-bring-your-own-validator)
26
+ 18. [Per-Field Async Validation (fieldValidators)](#per-field-async-validation-fieldvalidators)
27
+ 19. [Pattern-Matching Submit Results](#pattern-matching-submit-results)
28
+ 20. [Custom Field Components](#custom-field-components)
29
+ 21. [Performance Patterns](#performance-patterns)
30
+ 22. [UI Library Integration](#ui-library-integration)
31
+ 23. [Testing Forms](#testing-forms)
32
+ 24. [Form State Persistence](#form-state-persistence)
33
+ 25. [Unsaved Changes Warning](#unsaved-changes-warning)
34
+ 26. [Capstone: Full Registration Form (Result Pattern)](#capstone-full-registration-form-result-pattern)
35
+ 27. [Capstone: Full Registration Form (React Query)](#capstone-full-registration-form-react-query)
36
+
37
+ ---
38
+
39
+ ## CRUD Form with Server Errors
40
+
41
+ **Problem:** You're building a create/edit form that talks to an API. The server might reject the data (duplicate email, username taken), and you need those errors to appear on the correct fields.
42
+
43
+ **Solution:** Use `onSubmit` to call the API, and `setServerErrors` to display backend validation errors. Server errors auto-clear when the user edits the affected field.
44
+
45
+ ```tsx
46
+ import { useForm } from '@railway-ts/use-form';
47
+ import {
48
+ object,
49
+ string,
50
+ required,
51
+ optional,
52
+ chain,
53
+ nonEmpty,
54
+ minLength,
55
+ email,
56
+ ROOT_ERROR_KEY,
57
+ type InferSchemaType,
58
+ } from '@railway-ts/pipelines/schema';
59
+
60
+ const userSchema = object({
61
+ username: required(chain(string(), nonEmpty(), minLength(3))),
62
+ email: required(chain(string(), nonEmpty(), email())),
63
+ bio: optional(string()),
64
+ });
65
+
66
+ type UserForm = InferSchemaType<typeof userSchema>;
67
+
68
+ function CreateUserForm() {
69
+ const form = useForm<UserForm>(userSchema, {
70
+ initialValues: { username: '', email: '', bio: '' },
71
+ onSubmit: async (values) => {
72
+ const response = await fetch('/api/users', {
73
+ method: 'POST',
74
+ headers: { 'Content-Type': 'application/json' },
75
+ body: JSON.stringify(values),
76
+ });
77
+
78
+ if (!response.ok) {
79
+ const errors = await response.json();
80
+ // e.g. { email: "Email already exists", username: "Username taken" }
81
+ form.setServerErrors(errors);
82
+ return;
83
+ }
84
+
85
+ window.location.reassign = '/users';
86
+ },
87
+ });
88
+
89
+ return (
90
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
91
+ <div>
92
+ <label htmlFor="field-username">Username</label>
93
+ <input {...form.getFieldProps('username')} />
94
+ {form.touched.username && form.errors.username && (
95
+ <span className="error">{form.errors.username}</span>
96
+ )}
97
+ </div>
98
+
99
+ <div>
100
+ <label htmlFor="field-email">Email</label>
101
+ <input type="email" {...form.getFieldProps('email')} />
102
+ {form.touched.email && form.errors.email && (
103
+ <span className="error">{form.errors.email}</span>
104
+ )}
105
+ </div>
106
+
107
+ <div>
108
+ <label htmlFor="field-bio">Bio</label>
109
+ <textarea {...form.getFieldProps('bio')} rows={4} />
110
+ </div>
111
+
112
+ {/* Form-level errors (not tied to a field) */}
113
+ {form.errors[ROOT_ERROR_KEY] && (
114
+ <div className="form-error">{form.errors[ROOT_ERROR_KEY]}</div>
115
+ )}
116
+
117
+ <button type="submit" disabled={form.isSubmitting}>
118
+ {form.isSubmitting ? 'Saving...' : 'Create User'}
119
+ </button>
120
+
121
+ <button
122
+ type="button"
123
+ onClick={() => form.resetForm()}
124
+ disabled={!form.isDirty}
125
+ >
126
+ Reset
127
+ </button>
128
+ </form>
129
+ );
130
+ }
131
+ ```
132
+
133
+ For form-level errors (network failures, rate limiting), use `ROOT_ERROR_KEY`:
134
+
135
+ ```typescript
136
+ form.setServerErrors({ [ROOT_ERROR_KEY]: 'Network error. Please try again.' });
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Nested Objects
142
+
143
+ **Problem:** Your form has structured data like an address inside a profile.
144
+
145
+ **Solution:** Use `object()` nesting in the schema and dot-notation paths everywhere.
146
+
147
+ ```tsx
148
+ const addressSchema = object({
149
+ street: required(string()),
150
+ city: required(string()),
151
+ state: required(string()),
152
+ zip: required(string()),
153
+ });
154
+
155
+ const profileSchema = object({
156
+ name: required(string()),
157
+ email: required(email()),
158
+ address: required(addressSchema),
159
+ });
160
+
161
+ type Profile = InferSchemaType<typeof profileSchema>;
162
+
163
+ function ProfileForm() {
164
+ const form = useForm<Profile>(profileSchema, {
165
+ initialValues: {
166
+ name: '',
167
+ email: '',
168
+ address: { street: '', city: '', state: '', zip: '' },
169
+ },
170
+ });
171
+
172
+ return (
173
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
174
+ <input {...form.getFieldProps('name')} placeholder="Name" />
175
+ <input {...form.getFieldProps('email')} placeholder="Email" />
176
+
177
+ <fieldset>
178
+ <legend>Address</legend>
179
+ <input {...form.getFieldProps('address.street')} placeholder="Street" />
180
+ <input {...form.getFieldProps('address.city')} placeholder="City" />
181
+ <input {...form.getFieldProps('address.state')} placeholder="State" />
182
+ <input {...form.getFieldProps('address.zip')} placeholder="ZIP" />
183
+ </fieldset>
184
+
185
+ <button type="submit">Save</button>
186
+ </form>
187
+ );
188
+ }
189
+ ```
190
+
191
+ Errors and touched state also use dot notation: `form.errors['address.city']`, `form.touched['address.zip']`.
192
+
193
+ ---
194
+
195
+ ## Dynamic Arrays
196
+
197
+ **Problem:** You need a list that users can add to, remove from, and reorder -- like contacts, line items, or todo lists.
198
+
199
+ **Solution:** `arrayHelpers` gives you mutation methods and field bindings for each item.
200
+
201
+ ```tsx
202
+ const todosSchema = object({
203
+ todos: array(
204
+ object({
205
+ text: required(chain(string(), nonEmpty('Task is required'))),
206
+ done: required(boolean()),
207
+ })
208
+ ),
209
+ });
210
+
211
+ type TodosForm = InferSchemaType<typeof todosSchema>;
212
+
213
+ function TodoList() {
214
+ const form = useForm<TodosForm>(todosSchema, {
215
+ initialValues: { todos: [] },
216
+ });
217
+
218
+ const helpers = form.arrayHelpers('todos');
219
+
220
+ return (
221
+ <div>
222
+ {helpers.values.map((todo, index) => (
223
+ <div key={index}>
224
+ <input type="checkbox" {...helpers.getCheckboxProps(index, 'done')} />
225
+ <input {...helpers.getFieldProps(index, 'text')} />
226
+
227
+ <button
228
+ onClick={() => index > 0 && helpers.swap(index, index - 1)}
229
+ disabled={index === 0}
230
+ >
231
+ Up
232
+ </button>
233
+ <button
234
+ onClick={() =>
235
+ index < helpers.values.length - 1 &&
236
+ helpers.swap(index, index + 1)
237
+ }
238
+ disabled={index === helpers.values.length - 1}
239
+ >
240
+ Down
241
+ </button>
242
+ <button onClick={() => helpers.remove(index)}>Delete</button>
243
+ </div>
244
+ ))}
245
+
246
+ <button onClick={() => helpers.push({ text: '', done: false })}>
247
+ Add Todo
248
+ </button>
249
+ </div>
250
+ );
251
+ }
252
+ ```
253
+
254
+ **Bulk operations** work by calling helpers in sequence:
255
+
256
+ ```typescript
257
+ // Add multiple items
258
+ const newTasks = [
259
+ { text: 'Task 1', done: false },
260
+ { text: 'Task 2', done: false },
261
+ ];
262
+ newTasks.forEach((task) => helpers.push(task));
263
+
264
+ // Remove completed items (iterate in reverse to avoid index shifting)
265
+ for (let i = helpers.values.length - 1; i >= 0; i--) {
266
+ if (helpers.values[i].done) helpers.remove(i);
267
+ }
268
+
269
+ // Mark all complete
270
+ helpers.values.forEach((_, index) => {
271
+ form.setFieldValue(`todos.${index}.done`, true);
272
+ });
273
+ ```
274
+
275
+ ---
276
+
277
+ ## Checkbox and Radio Groups
278
+
279
+ **Problem:** You need a group of checkboxes (multi-select into an array) or radio buttons (single-select from a set).
280
+
281
+ **Solution:** Use `getCheckboxGroupOptionProps` for checkboxes and `getRadioGroupOptionProps` for radios.
282
+
283
+ | Use case | Helper | Field type |
284
+ | -------------------------------- | ------------------------------------------- | ------------------------ |
285
+ | Multi-select (tags, permissions) | `getCheckboxGroupOptionProps(field, value)` | `string[]` or `number[]` |
286
+ | Single-select (theme, role) | `getRadioGroupOptionProps(field, value)` | `string` or `number` |
287
+ | Boolean toggle | `getCheckboxProps(field)` | `boolean` |
288
+
289
+ ```tsx
290
+ const prefsSchema = object({
291
+ notifications: array(stringEnum(['email', 'sms', 'push'])),
292
+ theme: required(stringEnum(['light', 'dark', 'auto'])),
293
+ });
294
+
295
+ type Preferences = InferSchemaType<typeof prefsSchema>;
296
+
297
+ function PreferencesForm() {
298
+ const form = useForm<Preferences>(prefsSchema, {
299
+ initialValues: { notifications: [], theme: 'light' },
300
+ });
301
+
302
+ return (
303
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
304
+ <fieldset>
305
+ <legend>Notify me via</legend>
306
+ {(['email', 'sms', 'push'] as const).map((method) => (
307
+ <label key={method}>
308
+ <input
309
+ type="checkbox"
310
+ {...form.getCheckboxGroupOptionProps('notifications', method)}
311
+ />
312
+ {method.charAt(0).toUpperCase() + method.slice(1)}
313
+ </label>
314
+ ))}
315
+ </fieldset>
316
+
317
+ <fieldset>
318
+ <legend>Theme</legend>
319
+ {(['light', 'dark', 'auto'] as const).map((theme) => (
320
+ <label key={theme}>
321
+ <input
322
+ type="radio"
323
+ {...form.getRadioGroupOptionProps('theme', theme)}
324
+ />
325
+ {theme.charAt(0).toUpperCase() + theme.slice(1)}
326
+ </label>
327
+ ))}
328
+ </fieldset>
329
+
330
+ <button type="submit">Save Preferences</button>
331
+ </form>
332
+ );
333
+ }
334
+ ```
335
+
336
+ ---
337
+
338
+ ## File Uploads
339
+
340
+ **Problem:** You need a file input with validation (type, size).
341
+
342
+ **Solution:** Use `getFileFieldProps` and chain `refine` predicates for validation. `required()` handles the "no file selected" case; each `refine` handles one check.
343
+
344
+ ```tsx
345
+ import { chain, refine } from '@railway-ts/pipelines/schema';
346
+
347
+ const fileValidator = chain(
348
+ refine<File>((value) => value instanceof File, 'Must be a file'),
349
+ refine<File>((value) => value.size <= 5_000_000, 'File too large (max 5MB)'),
350
+ refine<File>((value) => value.type.startsWith('image/'), 'Must be an image'),
351
+ );
352
+
353
+ const uploadSchema = object({
354
+ avatar: required(fileValidator),
355
+ });
356
+
357
+ type UploadForm = InferSchemaType<typeof uploadSchema>;
358
+
359
+ function AvatarUpload() {
360
+ const form = useForm<UploadForm>(uploadSchema, {
361
+ initialValues: { avatar: null },
362
+ onSubmit: async (values) => {
363
+ const formData = new FormData();
364
+ formData.append('avatar', values.avatar);
365
+ await fetch('/api/upload', { method: 'POST', body: formData });
366
+ },
367
+ });
368
+
369
+ return (
370
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
371
+ <input
372
+ type="file"
373
+ accept="image/*"
374
+ {...form.getFileFieldProps('avatar')}
375
+ />
376
+ {form.touched.avatar && form.errors.avatar && (
377
+ <span>{form.errors.avatar}</span>
378
+ )}
379
+ <button type="submit">Upload</button>
380
+ </form>
381
+ );
382
+ }
383
+ ```
384
+
385
+ Error paths are handled automatically: `object()` constructs the field path (e.g., `["avatar"]`) and passes it through `required()` -> `chain()` -> `refine()`. No manual path construction needed.
386
+
387
+ ---
388
+
389
+ ## Auto-Submit and Debounced Search
390
+
391
+ **Problem:** You want the form to submit automatically when values change -- for search boxes or filter panels.
392
+
393
+ **Solution:** `useFormAutoSubmission` watches form values and triggers `handleSubmit` after a debounce delay. For manual control, `useDebounce` wraps any callback.
394
+
395
+ | Tool | Use case | How it works |
396
+ | ------------------------------------ | ----------------------- | --------------------------------------------------------------------------- |
397
+ | `useFormAutoSubmission(form, delay)` | Auto-submit entire form | Watches `values`, waits `delay` ms, calls `handleSubmit` if valid and dirty |
398
+ | `useDebounce(callback, delay)` | Debounce any function | Returns debounced version that resets timer on each call |
399
+
400
+ ```tsx
401
+ import { useForm, useFormAutoSubmission } from '@railway-ts/use-form';
402
+
403
+ function ProductFilters() {
404
+ const form = useForm(filterSchema, {
405
+ initialValues: {
406
+ search: '',
407
+ category: '',
408
+ minPrice: undefined,
409
+ maxPrice: undefined,
410
+ },
411
+ onSubmit: async (values) => {
412
+ const params = new URLSearchParams();
413
+ if (values.search) params.set('search', values.search);
414
+ if (values.category) params.set('category', values.category);
415
+ await fetch(`/api/products?${params}`);
416
+ },
417
+ validationMode: 'live',
418
+ });
419
+
420
+ // Auto-submit 500ms after the user stops typing
421
+ useFormAutoSubmission(form, 500);
422
+
423
+ return (
424
+ <div>
425
+ <input {...form.getFieldProps('search')} placeholder="Search..." />
426
+ <select {...form.getSelectFieldProps('category')}>
427
+ <option value="">All Categories</option>
428
+ <option value="electronics">Electronics</option>
429
+ <option value="clothing">Clothing</option>
430
+ </select>
431
+ </div>
432
+ );
433
+ }
434
+ ```
435
+
436
+ For a simple search box where you want to control the callback directly:
437
+
438
+ ```tsx
439
+ import { useForm, useDebounce } from '@railway-ts/use-form';
440
+
441
+ function SearchBox() {
442
+ const form = useForm(searchSchema, {
443
+ initialValues: { query: '' },
444
+ });
445
+
446
+ const debouncedSearch = useDebounce((query: string) => {
447
+ fetch(`/api/search?q=${query}`);
448
+ }, 300);
449
+
450
+ return (
451
+ <input
452
+ {...form.getFieldProps('query')}
453
+ onChange={(e) => {
454
+ form.setFieldValue('query', e.target.value);
455
+ debouncedSearch(e.target.value);
456
+ }}
457
+ placeholder="Search..."
458
+ />
459
+ );
460
+ }
461
+ ```
462
+
463
+ ---
464
+
465
+ ## Multi-Step Wizard
466
+
467
+ **Problem:** You have a long form split into steps. Each step should validate independently.
468
+
469
+ **Solution:** Use a single `useForm` with all fields. Validate on each "Next" click with `validateForm`, advance only if valid.
470
+
471
+ ```tsx
472
+ import { useState } from 'react';
473
+ import { isOk } from '@railway-ts/pipelines/result';
474
+
475
+ function MultiStepForm() {
476
+ const [step, setStep] = useState(1);
477
+
478
+ const form = useForm(wizardSchema, {
479
+ initialValues: {
480
+ personal: { name: '', email: '' },
481
+ address: { street: '', city: '' },
482
+ payment: { cardNumber: '' },
483
+ },
484
+ onSubmit: async (values) => {
485
+ await fetch('/api/orders', {
486
+ method: 'POST',
487
+ body: JSON.stringify(values),
488
+ });
489
+ },
490
+ });
491
+
492
+ const handleNext = () => {
493
+ const result = form.validateForm(form.values);
494
+ if (isOk(result)) setStep(step + 1);
495
+ };
496
+
497
+ // Note: validateForm validates all fields, not just the current step.
498
+ // This works here because each step only renders its own error messages.
499
+ // If you need per-step validation gating (e.g., disable "Next" until
500
+ // the current step is valid), check only the current step's fields in the result.
501
+
502
+ return (
503
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
504
+ {step === 1 && (
505
+ <div>
506
+ <h2>Personal Info</h2>
507
+ <input {...form.getFieldProps('personal.name')} placeholder="Name" />
508
+ <input
509
+ {...form.getFieldProps('personal.email')}
510
+ placeholder="Email"
511
+ />
512
+ <button type="button" onClick={handleNext}>
513
+ Next
514
+ </button>
515
+ </div>
516
+ )}
517
+
518
+ {step === 2 && (
519
+ <div>
520
+ <h2>Address</h2>
521
+ <input
522
+ {...form.getFieldProps('address.street')}
523
+ placeholder="Street"
524
+ />
525
+ <input {...form.getFieldProps('address.city')} placeholder="City" />
526
+ <button type="button" onClick={() => setStep(1)}>
527
+ Back
528
+ </button>
529
+ <button type="button" onClick={handleNext}>
530
+ Next
531
+ </button>
532
+ </div>
533
+ )}
534
+
535
+ {step === 3 && (
536
+ <div>
537
+ <h2>Payment</h2>
538
+ <input
539
+ {...form.getFieldProps('payment.cardNumber')}
540
+ placeholder="Card Number"
541
+ />
542
+ <button type="button" onClick={() => setStep(2)}>
543
+ Back
544
+ </button>
545
+ <button type="submit">Submit</button>
546
+ </div>
547
+ )}
548
+ </form>
549
+ );
550
+ }
551
+ ```
552
+
553
+ ---
554
+
555
+ ## Dependent Fields / Cross-Field Validation
556
+
557
+ **Problem:** A field's validity depends on another field -- password confirmation, date ranges, conditional requirements.
558
+
559
+ **Solution:** Use `refineAt` from `@railway-ts/pipelines/schema`. It runs after the object validates, receives the whole object, and attaches the error to a specific field path.
560
+
561
+ ```typescript
562
+ import {
563
+ object,
564
+ string,
565
+ required,
566
+ chain,
567
+ refineAt,
568
+ minLength,
569
+ type InferSchemaType,
570
+ } from '@railway-ts/pipelines/schema';
571
+
572
+ const registrationSchema = chain(
573
+ object({
574
+ password: required(chain(string(), minLength(8))),
575
+ confirmPassword: required(string()),
576
+ startDate: required(string()),
577
+ endDate: required(string()),
578
+ }),
579
+ refineAt(
580
+ 'confirmPassword',
581
+ (data) => data.password === data.confirmPassword,
582
+ 'Passwords must match'
583
+ ),
584
+ refineAt(
585
+ 'endDate',
586
+ (data) => {
587
+ if (!data.startDate || !data.endDate) return true;
588
+ return new Date(data.endDate) > new Date(data.startDate);
589
+ },
590
+ 'End date must be after start date'
591
+ )
592
+ );
593
+
594
+ type RegistrationData = InferSchemaType<typeof registrationSchema>;
595
+ ```
596
+
597
+ The key insight: `chain` at the **object level** (not the field level) gives `refineAt` access to all fields. The first argument to `refineAt` is the field path where the error should appear.
598
+
599
+ ---
600
+
601
+ ## Conditional Validation
602
+
603
+ **Problem:** Some fields are only required based on another field's value -- like company name and tax ID for business accounts.
604
+
605
+ **Solution:** Same technique as cross-field validation. Use `refineAt` to conditionally require fields.
606
+
607
+ ```tsx
608
+ const accountSchema = chain(
609
+ object({
610
+ accountType: required(stringEnum(['personal', 'business'])),
611
+ companyName: optional(string()),
612
+ taxId: optional(string()),
613
+ }),
614
+ refineAt(
615
+ 'companyName',
616
+ (data) => data.accountType === 'personal' || !!data.companyName,
617
+ 'Company name is required for business accounts'
618
+ ),
619
+ refineAt(
620
+ 'taxId',
621
+ (data) => data.accountType === 'personal' || !!data.taxId,
622
+ 'Tax ID is required for business accounts'
623
+ )
624
+ );
625
+
626
+ type AccountData = InferSchemaType<typeof accountSchema>;
627
+
628
+ function AccountForm() {
629
+ const form = useForm<AccountData>(accountSchema, {
630
+ initialValues: { accountType: 'personal', companyName: '', taxId: '' },
631
+ });
632
+
633
+ const isBusiness = form.values.accountType === 'business';
634
+
635
+ return (
636
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
637
+ <select {...form.getSelectFieldProps('accountType')}>
638
+ <option value="personal">Personal</option>
639
+ <option value="business">Business</option>
640
+ </select>
641
+
642
+ {isBusiness && (
643
+ <>
644
+ <input
645
+ {...form.getFieldProps('companyName')}
646
+ placeholder="Company Name"
647
+ />
648
+ {form.touched.companyName && form.errors.companyName && (
649
+ <span>{form.errors.companyName}</span>
650
+ )}
651
+
652
+ <input {...form.getFieldProps('taxId')} placeholder="Tax ID" />
653
+ {form.touched.taxId && form.errors.taxId && (
654
+ <span>{form.errors.taxId}</span>
655
+ )}
656
+ </>
657
+ )}
658
+
659
+ <button type="submit">Create Account</button>
660
+ </form>
661
+ );
662
+ }
663
+ ```
664
+
665
+ ---
666
+
667
+ ## Discriminated Unions
668
+
669
+ **Problem:** Your form's shape changes based on a discriminator field -- payment method, account type, entity kind.
670
+
671
+ **Solution:** Use `discriminatedUnion` from `@railway-ts/pipelines/schema`. Field path autocomplete includes paths from **all variants**, so `getFieldProps` works regardless of which variant is active.
672
+
673
+ ```typescript
674
+ import { discriminatedUnion, literal } from '@railway-ts/pipelines/schema';
675
+
676
+ const paymentSchema = discriminatedUnion('method', {
677
+ card: object({
678
+ method: literal('card'),
679
+ cardNumber: required(chain(string(), nonEmpty())),
680
+ expiryDate: required(string()),
681
+ cvv: required(string()),
682
+ }),
683
+ paypal: object({
684
+ method: literal('paypal'),
685
+ email: required(email()),
686
+ }),
687
+ bank: object({
688
+ method: literal('bank'),
689
+ accountNumber: required(string()),
690
+ routingNumber: required(string()),
691
+ }),
692
+ });
693
+
694
+ type Payment = InferSchemaType<typeof paymentSchema>;
695
+ ```
696
+
697
+ ```tsx
698
+ function PaymentForm() {
699
+ const form = useForm<Payment>(paymentSchema, {
700
+ initialValues: { method: 'card', cardNumber: '', expiryDate: '', cvv: '' },
701
+ });
702
+
703
+ const method = form.values.method;
704
+
705
+ return (
706
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
707
+ <select {...form.getSelectFieldProps('method')}>
708
+ <option value="card">Credit Card</option>
709
+ <option value="paypal">PayPal</option>
710
+ <option value="bank">Bank Transfer</option>
711
+ </select>
712
+
713
+ {method === 'card' && (
714
+ <>
715
+ <input
716
+ {...form.getFieldProps('cardNumber')}
717
+ placeholder="Card Number"
718
+ />
719
+ <input {...form.getFieldProps('expiryDate')} placeholder="MM/YY" />
720
+ <input {...form.getFieldProps('cvv')} placeholder="CVV" />
721
+ </>
722
+ )}
723
+
724
+ {method === 'paypal' && (
725
+ <input {...form.getFieldProps('email')} placeholder="PayPal Email" />
726
+ )}
727
+
728
+ {method === 'bank' && (
729
+ <>
730
+ <input
731
+ {...form.getFieldProps('accountNumber')}
732
+ placeholder="Account Number"
733
+ />
734
+ <input
735
+ {...form.getFieldProps('routingNumber')}
736
+ placeholder="Routing Number"
737
+ />
738
+ </>
739
+ )}
740
+
741
+ <button type="submit">Pay</button>
742
+ </form>
743
+ );
744
+ }
745
+ ```
746
+
747
+ `ExtractFieldPaths<Payment>` includes paths from all variants -- `'method' | 'cardNumber' | 'expiryDate' | 'cvv' | 'email' | 'accountNumber' | 'routingNumber'`.
748
+
749
+ ---
750
+
751
+ ## Custom Validators
752
+
753
+ **Problem:** You need reusable validation functions beyond what's built in -- strong passwords, phone numbers, credit card numbers.
754
+
755
+ **Solution:** Create validators with `refine`. The predicate receives the typed value and returns a boolean -- the library handles error creation and path resolution internally.
756
+
757
+ ```typescript
758
+ import { refine } from '@railway-ts/pipelines/schema';
759
+
760
+ const strongPassword = (message = 'Password is too weak') =>
761
+ refine<string>((value) => {
762
+ const hasUpper = /[A-Z]/.test(value);
763
+ const hasLower = /[a-z]/.test(value);
764
+ const hasNumber = /[0-9]/.test(value);
765
+ const hasSpecial = /[!@#$%^&*]/.test(value);
766
+ const isLongEnough = value.length >= 8;
767
+
768
+ return hasUpper && hasLower && hasNumber && hasSpecial && isLongEnough;
769
+ }, message);
770
+
771
+ const phoneNumber = (message = 'Invalid phone number') =>
772
+ refine<string>((value) => {
773
+ const cleaned = value.replace(/\D/g, '');
774
+ return cleaned.length === 10;
775
+ }, message);
776
+
777
+ const creditCard = (message = 'Invalid credit card') =>
778
+ refine<string>((value) => {
779
+ const cleaned = value.replace(/\s/g, '');
780
+ if (!/^\d{13,19}$/.test(cleaned)) return false;
781
+
782
+ // Luhn algorithm
783
+ let sum = 0;
784
+ let isEven = false;
785
+ for (let i = cleaned.length - 1; i >= 0; i--) {
786
+ let digit = parseInt(cleaned[i]);
787
+ if (isEven) {
788
+ digit *= 2;
789
+ if (digit > 9) digit -= 9;
790
+ }
791
+ sum += digit;
792
+ isEven = !isEven;
793
+ }
794
+ return sum % 10 === 0;
795
+ }, message);
796
+
797
+ // Use in schemas
798
+ const schema = object({
799
+ password: required(chain(string(), strongPassword())),
800
+ phone: optional(chain(string(), phoneNumber())),
801
+ card: optional(chain(string(), creditCard())),
802
+ });
803
+ ```
804
+
805
+ `refine` validates a single field -- it receives the field's value and the error attaches to that field automatically. For cross-field validation (where you need access to the entire object), use `refineAt` instead -- see the [API Reference](./API.md#refineat).
806
+
807
+ ---
808
+
809
+ ## Programmatic Field Updates
810
+
811
+ **Problem:** You need to update computed fields (totals, derived values) without triggering validation.
812
+
813
+ **Solution:** Pass `false` as the third argument to `setFieldValue` to skip validation.
814
+
815
+ ```typescript
816
+ function CalculatorForm() {
817
+ const form = useForm(calculatorSchema, {
818
+ initialValues: { quantity: 0, price: 0, total: 0 },
819
+ });
820
+
821
+ useEffect(() => {
822
+ const total = (form.values.quantity || 0) * (form.values.price || 0);
823
+ form.setFieldValue('total', total, false); // false = skip validation
824
+ }, [form.values.quantity, form.values.price]);
825
+
826
+ return (
827
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
828
+ <input type="number" {...form.getFieldProps('quantity')} />
829
+ <input type="number" {...form.getFieldProps('price')} />
830
+ <input type="number" {...form.getFieldProps('total')} readOnly />
831
+ <button type="submit">Submit</button>
832
+ </form>
833
+ );
834
+ }
835
+ ```
836
+
837
+ ---
838
+
839
+ ## Syncing Values to External State
840
+
841
+ **Problem:** You need to keep an external store (Zustand, Redux, URL params)
842
+ in sync with form values without per-field `useEffect` hooks.
843
+
844
+ **Solution:** Use `onValuesChange` with `prevValues` for efficient diffing.
845
+
846
+ ```tsx
847
+ const form = useForm(missionSchema, {
848
+ initialValues: { altitude: 400, velocity: 8, name: '' },
849
+ onValuesChange: (values, prev) => {
850
+ if (values.altitude !== prev.altitude) {
851
+ missionStore.setAltitude(Number(values.altitude));
852
+ }
853
+ if (values.velocity !== prev.velocity) {
854
+ missionStore.setVelocity(Number(values.velocity));
855
+ }
856
+ },
857
+ onSubmit: launchMission,
858
+ });
859
+ ```
860
+
861
+ For simple cases where the sync is cheap (e.g., Zustand setters are no-ops
862
+ when the value hasn't changed), you can skip the diff:
863
+
864
+ ```tsx
865
+ onValuesChange: (values) => {
866
+ missionStore.setAltitude(Number(values.altitude));
867
+ missionStore.setVelocity(Number(values.velocity));
868
+ },
869
+ ```
870
+
871
+ > **Note:** Fires on mount with `(initialValues, initialValues)`. If your
872
+ > store is already seeded, this is a no-op.
873
+
874
+ ---
875
+
876
+ ## Reacting to Individual Field Changes
877
+
878
+ **Problem:** You want to run a side effect when a specific field changes —
879
+ analytics tracking, conditional field visibility, dependent field updates —
880
+ without watching the entire form.
881
+
882
+ **Solution:** Use `onFieldChange` for per-field reactions.
883
+
884
+ ```tsx
885
+ const form = useForm(schema, {
886
+ initialValues: { country: '', state: '', zip: '' },
887
+ onFieldChange: (field, value, values) => {
888
+ // Clear dependent fields when country changes
889
+ if (field === 'country') {
890
+ form.setFieldValue('state', '');
891
+ form.setFieldValue('zip', '');
892
+ }
893
+ // Track field interactions
894
+ analytics.track('field_edited', { field, formId: 'checkout' });
895
+ },
896
+ onSubmit: handleCheckout,
897
+ });
898
+ ```
899
+
900
+ `onFieldChange` fires from all native bindings (inputs, selects, checkboxes,
901
+ sliders, radios, file inputs) and array helper operations (`push`, `remove`,
902
+ `insert`, `swap`, `replace`). It does **not** fire for batch updates via
903
+ `setValues` or `resetForm` — use `onValuesChange` for those.
904
+
905
+ ---
906
+
907
+ ## submitCount Patterns
908
+
909
+ **Problem:** In `submit` validation mode, the submit button starts disabled even though the user hasn't tried submitting yet.
910
+
911
+ **Solution:** Use `submitCount` to distinguish "hasn't submitted yet" from "submitted with errors." Before the first submit, keep the button enabled; after a failed submit, disable until errors are fixed.
912
+
913
+ ```tsx
914
+ const form = useForm(schema, {
915
+ initialValues: {
916
+ /* ... */
917
+ },
918
+ validationMode: 'submit',
919
+ });
920
+
921
+ // Before first submit: button is enabled (haven't validated yet)
922
+ // After failed submit: button is disabled until errors are fixed
923
+ <button type="submit" disabled={form.submitCount > 0 && !form.isValid}>
924
+ Submit
925
+ </button>;
926
+ ```
927
+
928
+ ---
929
+
930
+ ## Understanding Error Priority
931
+
932
+ **Problem:** You're seeing unexpected error messages and need to understand which error layer takes precedence.
933
+
934
+ **Solution:** The `errors` object is a merged view of three separate layers. When multiple layers have an error for the same field, higher-priority layers win:
935
+
936
+ | Priority | Source | Property | Populated when |
937
+ | ----------- | ----------------- | -------------- | ------------------------------------------------------------------------------ |
938
+ | 1 (lowest) | Schema validation | `clientErrors` | Schema validator runs (on change, blur, mount, or submit depending on mode) |
939
+ | 2 | Field validators | `fieldErrors` | `fieldValidators` option runs for a field (after schema passes for that field) |
940
+ | 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)` |
941
+
942
+ **When each layer gets cleared:**
943
+
944
+ - `clientErrors` -- replaced on every schema validation run
945
+ - `fieldErrors` -- cleared per-field when the field validator re-runs or the field's schema error reappears
946
+ - `serverErrors` -- auto-cleared per-field when the user edits the affected field; bulk-cleared on `clearServerErrors()` or new `handleSubmit`
947
+
948
+ A server error stays visible until the user changes the field, even if client validation passes. That's intentional -- the server said it's wrong, and only editing should dismiss it.
949
+
950
+ For the full technical details, see the [API Reference: Error Priority](./API.md#error-priority).
951
+
952
+ ---
953
+
954
+ ## Standard Schema: Bring Your Own Validator
955
+
956
+ **Problem:** You already have Zod or Valibot schemas in your codebase and don't want to rewrite them.
957
+
958
+ **Solution:** Pass them directly to `useForm`. Any library that implements [Standard Schema v1](https://github.com/standard-schema/standard-schema) works without adapters.
959
+
960
+ ### Zod
961
+
962
+ ```tsx
963
+ import { z } from 'zod';
964
+ import { useForm } from '@railway-ts/use-form';
965
+
966
+ const userSchema = z.object({
967
+ username: z.string().min(3, 'Username must be at least 3 characters'),
968
+ email: z.email('Invalid email address'),
969
+ password: z.string().min(8, 'Password must be at least 8 characters'),
970
+ age: z.coerce.number().min(18, 'Must be at least 18').max(120),
971
+ role: z.enum(['admin', 'user']),
972
+ });
973
+
974
+ type User = z.infer<typeof userSchema>;
975
+
976
+ function ZodForm() {
977
+ const form = useForm<User>(userSchema, {
978
+ initialValues: {
979
+ username: '',
980
+ email: '',
981
+ password: '',
982
+ age: 0,
983
+ role: 'user',
984
+ },
985
+ onSubmit: (values) => console.log('Submit:', values),
986
+ });
987
+
988
+ return (
989
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
990
+ <input {...form.getFieldProps('username')} />
991
+ {form.touched.username && form.errors.username && (
992
+ <span>{form.errors.username}</span>
993
+ )}
994
+ {/* ... other fields ... */}
995
+ <button type="submit">Register</button>
996
+ </form>
997
+ );
998
+ }
999
+ ```
1000
+
1001
+ ### Valibot
1002
+
1003
+ ```tsx
1004
+ import * as v from 'valibot';
1005
+ import { useForm } from '@railway-ts/use-form';
1006
+
1007
+ const userSchema = v.object({
1008
+ username: v.pipe(
1009
+ v.string(),
1010
+ v.minLength(3, 'Username must be at least 3 characters')
1011
+ ),
1012
+ email: v.pipe(v.string(), v.email('Invalid email address')),
1013
+ password: v.pipe(
1014
+ v.string(),
1015
+ v.minLength(8, 'Password must be at least 8 characters')
1016
+ ),
1017
+ age: v.pipe(
1018
+ v.unknown(),
1019
+ v.transform(Number),
1020
+ v.number(),
1021
+ v.minValue(18, 'Must be at least 18')
1022
+ ),
1023
+ role: v.picklist(['admin', 'user']),
1024
+ });
1025
+
1026
+ type User = v.InferOutput<typeof userSchema>;
1027
+
1028
+ function ValibotForm() {
1029
+ const form = useForm<User>(userSchema, {
1030
+ initialValues: {
1031
+ username: '',
1032
+ email: '',
1033
+ password: '',
1034
+ age: 0,
1035
+ role: 'user',
1036
+ },
1037
+ onSubmit: (values) => console.log('Submit:', values),
1038
+ });
1039
+
1040
+ // Same JSX as above -- the hook API is identical regardless of validator
1041
+ // ...
1042
+ }
1043
+ ```
1044
+
1045
+ ### Comparison
1046
+
1047
+ | Feature | @railway-ts/pipelines | Zod | Valibot |
1048
+ | ---------------------- | ----------------------------- | -------------------------- | ------------------------ |
1049
+ | Error accumulation | All errors in one pass | First error per field | All errors in one pass |
1050
+ | Bundle size | ~4 KB | ~13 KB | ~7 KB |
1051
+ | Cross-field validation | `refineAt` (targeted) | `.refine` / `.superRefine` | `v.forward` + `v.custom` |
1052
+ | Async validation | `chainAsync`, `refineAtAsync` | `.refine` with async | `v.pipeAsync` |
1053
+ | Result type | Native `Result<T, E>` | Throws or `.safeParse` | Throws or `.safeParse` |
1054
+ | Standard Schema | `toStandardSchema()` | Native (v3.23+, v4) | Native (v1+) |
1055
+
1056
+ ---
1057
+
1058
+ ## Per-Field Async Validation (fieldValidators)
1059
+
1060
+ **Problem:** You need to check a value against the server (username availability, coupon codes) without blocking the entire form. Schema-level async validation (`chainAsync`) validates the whole form -- you want per-field control with per-field loading indicators.
1061
+
1062
+ **Solution:** The `fieldValidators` option runs independent async checks for specific fields. Each field validator only runs when the schema produces no error for that field, and `validatingFields` tracks which fields are currently checking.
1063
+
1064
+ ```tsx
1065
+ const checkUsernameAvailable = async (username: string): Promise<boolean> => {
1066
+ const res = await fetch(`/api/check-username?username=${username}`);
1067
+ const data = await res.json();
1068
+ return data.available;
1069
+ };
1070
+
1071
+ function RegistrationForm() {
1072
+ const form = useForm<UserForm>(userSchema, {
1073
+ initialValues: { username: '', email: '', password: '' },
1074
+ onSubmit: async (values) => {
1075
+ await fetch('/api/register', {
1076
+ method: 'POST',
1077
+ body: JSON.stringify(values),
1078
+ });
1079
+ },
1080
+ fieldValidators: {
1081
+ username: async (value) => {
1082
+ const available = await checkUsernameAvailable(value);
1083
+ return available ? undefined : 'Username is already taken';
1084
+ },
1085
+ },
1086
+ });
1087
+
1088
+ return (
1089
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1090
+ <div>
1091
+ <input {...form.getFieldProps('username')} />
1092
+ {form.validatingFields.username && (
1093
+ <span className="validating">Checking username...</span>
1094
+ )}
1095
+ {form.touched.username && form.errors.username && (
1096
+ <span className="error">{form.errors.username}</span>
1097
+ )}
1098
+ </div>
1099
+
1100
+ {/* ... other fields ... */}
1101
+
1102
+ <button type="submit" disabled={form.isSubmitting || form.isValidating}>
1103
+ Register
1104
+ </button>
1105
+ </form>
1106
+ );
1107
+ }
1108
+ ```
1109
+
1110
+ ### fieldValidators vs schema-level async
1111
+
1112
+ | | `fieldValidators` | `chainAsync` / `refineAtAsync` |
1113
+ | ------------------- | ---------------------------------- | ------------------------------ |
1114
+ | **Scope** | Single field | Entire form |
1115
+ | **Runs when** | After schema passes for that field | During schema validation |
1116
+ | **Loading state** | `validatingFields.fieldName` | `isValidating` (form-wide) |
1117
+ | **Race conditions** | Handled per-field (latest wins) | Handled per-form (latest wins) |
1118
+ | **Best for** | Server lookups (username, email) | Cross-field async checks |
1119
+
1120
+ Field validators return `undefined` for valid, or an error message string for invalid. They receive the typed field value and the full form values object: `(value: FieldTypeAtPath<TValues, K>, values: TValues) => string | undefined | Promise<string | undefined>` — no cast needed.
1121
+
1122
+ ---
1123
+
1124
+ ## Pattern-Matching Submit Results
1125
+
1126
+ **Problem:** You want to handle the submit outcome programmatically rather than through `onSubmit` -- for example, to navigate on success or log errors.
1127
+
1128
+ **Solution:** `handleSubmit` returns a `Promise<Result<TValues, ValidationError[]>>`. Use `match` from `@railway-ts/pipelines/result` to branch on success or failure.
1129
+
1130
+ ```tsx
1131
+ import { match } from '@railway-ts/pipelines/result';
1132
+
1133
+ function RegistrationForm() {
1134
+ const form = useForm(registrationSchema, {
1135
+ initialValues: { email: '', password: '' },
1136
+ // No onSubmit needed -- we handle the result directly
1137
+ });
1138
+
1139
+ const handleSave = async () => {
1140
+ const result = await form.handleSubmit();
1141
+
1142
+ match(result, {
1143
+ ok: (values) => {
1144
+ console.log('Validated data:', values);
1145
+ // Navigate, show toast, etc.
1146
+ },
1147
+ err: (errors) => {
1148
+ console.error('Validation failed:', errors);
1149
+ // Log to analytics, show banner, etc.
1150
+ },
1151
+ });
1152
+ };
1153
+
1154
+ return (
1155
+ <form
1156
+ onSubmit={(e) => {
1157
+ e.preventDefault();
1158
+ void handleSave();
1159
+ }}
1160
+ >
1161
+ <input type="email" {...form.getFieldProps('email')} />
1162
+ <input type="password" {...form.getFieldProps('password')} />
1163
+ <button type="submit">Register</button>
1164
+ </form>
1165
+ );
1166
+ }
1167
+ ```
1168
+
1169
+ You can also combine `onSubmit` (for the main action) with the returned `Result` (for side effects):
1170
+
1171
+ ```typescript
1172
+ const form = useForm(schema, {
1173
+ initialValues: {
1174
+ /* ... */
1175
+ },
1176
+ onSubmit: async (values) => {
1177
+ await api.createUser(values);
1178
+ },
1179
+ });
1180
+
1181
+ // Later, in a handler:
1182
+ const result = await form.handleSubmit();
1183
+ match(result, {
1184
+ ok: () => navigate('/dashboard'),
1185
+ err: () => scrollToFirstError(),
1186
+ });
1187
+ ```
1188
+
1189
+ ---
1190
+
1191
+ ## Custom Field Components
1192
+
1193
+ **Problem:** You're repeating the same label + input + error markup for every field.
1194
+
1195
+ **Solution:** Extract a reusable `Field` component that takes the form instance, field name, and label.
1196
+
1197
+ ```tsx
1198
+ import { useForm } from '@railway-ts/use-form';
1199
+ import {
1200
+ object,
1201
+ required,
1202
+ chain,
1203
+ string,
1204
+ email,
1205
+ minLength,
1206
+ type InferSchemaType,
1207
+ } from '@railway-ts/pipelines/schema';
1208
+
1209
+ const loginSchema = object({
1210
+ email: required(chain(string(), email())),
1211
+ password: required(chain(string(), minLength(8))),
1212
+ });
1213
+
1214
+ type LoginValues = InferSchemaType<typeof loginSchema>;
1215
+
1216
+ type FieldProps = {
1217
+ form: ReturnType<typeof useForm<LoginValues>>;
1218
+ name: keyof LoginValues & string;
1219
+ label: string;
1220
+ type?: string;
1221
+ };
1222
+
1223
+ function Field({ form, name, label, type = 'text' }: FieldProps) {
1224
+ const error = form.touched[name] && form.errors[name];
1225
+
1226
+ return (
1227
+ <div className="field">
1228
+ <label htmlFor={`field-${name}`}>{label}</label>
1229
+ <input type={type} {...form.getFieldProps(name)} />
1230
+ {error && <span className="error">{error}</span>}
1231
+ </div>
1232
+ );
1233
+ }
1234
+
1235
+ // Usage
1236
+ function LoginForm() {
1237
+ const form = useForm(loginSchema, {
1238
+ initialValues: { email: '', password: '' },
1239
+ });
1240
+
1241
+ return (
1242
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1243
+ <Field form={form} name="email" label="Email" type="email" />
1244
+ <Field form={form} name="password" label="Password" type="password" />
1245
+ <button type="submit">Submit</button>
1246
+ </form>
1247
+ );
1248
+ }
1249
+ ```
1250
+
1251
+ For more control, accept `children` or render props instead of hard-coding `<input>`.
1252
+
1253
+ ---
1254
+
1255
+ ## Performance Patterns
1256
+
1257
+ **Problem:** Large forms re-render the entire component tree on every keystroke.
1258
+
1259
+ ### Memoize Field Components
1260
+
1261
+ Wrap field components in `React.memo` so they only re-render when their specific field changes:
1262
+
1263
+ ```tsx
1264
+ import { memo, useMemo } from 'react';
1265
+ import { useForm } from '@railway-ts/use-form';
1266
+ import {
1267
+ object,
1268
+ required,
1269
+ string,
1270
+ type InferSchemaType,
1271
+ } from '@railway-ts/pipelines/schema';
1272
+
1273
+ const largeFormSchema = object({
1274
+ field1: required(string()),
1275
+ field2: required(string()),
1276
+ // ... more fields
1277
+ });
1278
+
1279
+ type LargeFormValues = InferSchemaType<typeof largeFormSchema>;
1280
+
1281
+ const MemoField = memo(function MemoField({
1282
+ form,
1283
+ name,
1284
+ label,
1285
+ }: {
1286
+ form: ReturnType<typeof useForm<LargeFormValues>>;
1287
+ name: keyof LargeFormValues & string;
1288
+ label: string;
1289
+ }) {
1290
+ const props = useMemo(() => form.getFieldProps(name), [form, name]);
1291
+ const error = form.touched[name] && form.errors[name];
1292
+
1293
+ return (
1294
+ <div>
1295
+ <label>{label}</label>
1296
+ <input {...props} />
1297
+ {error && <span>{error}</span>}
1298
+ </div>
1299
+ );
1300
+ });
1301
+
1302
+ function LargeForm() {
1303
+ const form = useForm(largeFormSchema, {
1304
+ initialValues: { field1: '', field2: '' },
1305
+ });
1306
+
1307
+ return (
1308
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1309
+ <MemoField form={form} name="field1" label="Field 1" />
1310
+ <MemoField form={form} name="field2" label="Field 2" />
1311
+ {/* Many more fields */}
1312
+ </form>
1313
+ );
1314
+ }
1315
+ ```
1316
+
1317
+ ### Use Blur Mode for Long Forms
1318
+
1319
+ For forms with many fields, `validationMode: 'blur'` avoids re-validating on every keystroke:
1320
+
1321
+ ```typescript
1322
+ const form = useForm(schema, {
1323
+ initialValues: {
1324
+ /* ... */
1325
+ },
1326
+ validationMode: 'blur',
1327
+ });
1328
+ ```
1329
+
1330
+ ### Debounce Expensive Side Effects
1331
+
1332
+ Use `useDebounce` to throttle callbacks triggered by form value changes:
1333
+
1334
+ ```tsx
1335
+ import { useDebounce } from '@railway-ts/use-form';
1336
+
1337
+ const debouncedSearch = useDebounce((query: string) => {
1338
+ fetch(`/api/search?q=${query}`);
1339
+ }, 300);
1340
+ ```
1341
+
1342
+ ---
1343
+
1344
+ ## UI Library Integration
1345
+
1346
+ UI libraries like Material-UI and Chakra UI use different prop names than native HTML. You need to manually map form state to their component APIs.
1347
+
1348
+ ### Which approach to use
1349
+
1350
+ | Library | Approach |
1351
+ | ------------------------------------------- | ----------------------------------------------------------- |
1352
+ | **Shadcn/ui, Radix, Headless UI** | `getFieldProps` works directly (native HTML under the hood) |
1353
+ | **Material-UI, Chakra UI (v3), Ant Design** | Map form state to component props manually |
1354
+
1355
+ ### Material-UI
1356
+
1357
+ ```tsx
1358
+ import { TextField, Button } from '@mui/material';
1359
+ import { useForm } from '@railway-ts/use-form';
1360
+ import {
1361
+ object,
1362
+ required,
1363
+ chain,
1364
+ string,
1365
+ email,
1366
+ minLength,
1367
+ type InferSchemaType,
1368
+ } from '@railway-ts/pipelines/schema';
1369
+
1370
+ const loginSchema = object({
1371
+ email: required(chain(string(), email())),
1372
+ password: required(chain(string(), minLength(8))),
1373
+ });
1374
+
1375
+ type LoginValues = InferSchemaType<typeof loginSchema>;
1376
+
1377
+ function MuiForm() {
1378
+ const form = useForm(loginSchema, {
1379
+ initialValues: { email: '', password: '' },
1380
+ });
1381
+
1382
+ return (
1383
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1384
+ <TextField
1385
+ label="Email"
1386
+ name="email"
1387
+ value={form.values.email || ''}
1388
+ onChange={(e) => form.setFieldValue('email', e.target.value)}
1389
+ onBlur={() => form.setFieldTouched('email')}
1390
+ error={form.touched.email && Boolean(form.errors.email)}
1391
+ helperText={form.touched.email && form.errors.email}
1392
+ fullWidth
1393
+ margin="normal"
1394
+ />
1395
+
1396
+ <TextField
1397
+ label="Password"
1398
+ type="password"
1399
+ name="password"
1400
+ value={form.values.password || ''}
1401
+ onChange={(e) => form.setFieldValue('password', e.target.value)}
1402
+ onBlur={() => form.setFieldTouched('password')}
1403
+ error={form.touched.password && Boolean(form.errors.password)}
1404
+ helperText={form.touched.password && form.errors.password}
1405
+ fullWidth
1406
+ margin="normal"
1407
+ />
1408
+
1409
+ <Button
1410
+ type="submit"
1411
+ variant="contained"
1412
+ disabled={form.isSubmitting || !form.isValid}
1413
+ >
1414
+ Submit
1415
+ </Button>
1416
+ </form>
1417
+ );
1418
+ }
1419
+ ```
1420
+
1421
+ ### Chakra UI (v3)
1422
+
1423
+ ```tsx
1424
+ import { Field, Input, Button } from '@chakra-ui/react';
1425
+ import { useForm } from '@railway-ts/use-form';
1426
+ import {
1427
+ object,
1428
+ required,
1429
+ chain,
1430
+ string,
1431
+ email,
1432
+ minLength,
1433
+ type InferSchemaType,
1434
+ } from '@railway-ts/pipelines/schema';
1435
+
1436
+ const loginSchema = object({
1437
+ email: required(chain(string(), email())),
1438
+ password: required(chain(string(), minLength(8))),
1439
+ });
1440
+
1441
+ type LoginValues = InferSchemaType<typeof loginSchema>;
1442
+
1443
+ function ChakraForm() {
1444
+ const form = useForm(loginSchema, {
1445
+ initialValues: { email: '', password: '' },
1446
+ });
1447
+
1448
+ return (
1449
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1450
+ <Field.Root invalid={form.touched.email && Boolean(form.errors.email)}>
1451
+ <Field.Label>Email</Field.Label>
1452
+ <Input
1453
+ name="email"
1454
+ value={form.values.email || ''}
1455
+ onChange={(e) => form.setFieldValue('email', e.target.value)}
1456
+ onBlur={() => form.setFieldTouched('email')}
1457
+ />
1458
+ <Field.ErrorText>{form.errors.email}</Field.ErrorText>
1459
+ </Field.Root>
1460
+
1461
+ <Button
1462
+ type="submit"
1463
+ loading={form.isSubmitting}
1464
+ disabled={!form.isValid}
1465
+ >
1466
+ Submit
1467
+ </Button>
1468
+ </form>
1469
+ );
1470
+ }
1471
+ ```
1472
+
1473
+ ### Shadcn/ui
1474
+
1475
+ Shadcn components use native HTML under the hood, so `getFieldProps` works directly:
1476
+
1477
+ ```tsx
1478
+ import { Input } from '@/components/ui/input';
1479
+ import { Label } from '@/components/ui/label';
1480
+ import { Button } from '@/components/ui/button';
1481
+ import { useForm } from '@railway-ts/use-form';
1482
+ import {
1483
+ object,
1484
+ required,
1485
+ chain,
1486
+ string,
1487
+ email,
1488
+ minLength,
1489
+ type InferSchemaType,
1490
+ } from '@railway-ts/pipelines/schema';
1491
+
1492
+ const loginSchema = object({
1493
+ email: required(chain(string(), email())),
1494
+ password: required(chain(string(), minLength(8))),
1495
+ });
1496
+
1497
+ type LoginValues = InferSchemaType<typeof loginSchema>;
1498
+
1499
+ function ShadcnForm() {
1500
+ const form = useForm(loginSchema, {
1501
+ initialValues: { email: '', password: '' },
1502
+ });
1503
+
1504
+ return (
1505
+ <form onSubmit={(e) => void form.handleSubmit(e)} className="space-y-4">
1506
+ <div>
1507
+ <Label htmlFor="field-email">Email</Label>
1508
+ <Input {...form.getFieldProps('email')} />
1509
+ {form.touched.email && form.errors.email && (
1510
+ <p className="text-sm text-destructive">{form.errors.email}</p>
1511
+ )}
1512
+ </div>
1513
+
1514
+ <div>
1515
+ <Label htmlFor="field-password">Password</Label>
1516
+ <Input type="password" {...form.getFieldProps('password')} />
1517
+ {form.touched.password && form.errors.password && (
1518
+ <p className="text-sm text-destructive">{form.errors.password}</p>
1519
+ )}
1520
+ </div>
1521
+
1522
+ <Button type="submit" disabled={form.isSubmitting || !form.isValid}>
1523
+ Submit
1524
+ </Button>
1525
+ </form>
1526
+ );
1527
+ }
1528
+ ```
1529
+
1530
+ ---
1531
+
1532
+ ## Testing Forms
1533
+
1534
+ **Problem:** You want to test form behavior -- validation errors, submission, server error handling.
1535
+
1536
+ **Solution:** Use Testing Library to render the form, interact with it, and assert on the output.
1537
+
1538
+ ```typescript
1539
+ import { describe, test, expect, mock } from 'bun:test';
1540
+ import { render, screen, waitFor } from '@testing-library/react';
1541
+ import userEvent from '@testing-library/user-event';
1542
+
1543
+ describe('LoginForm', () => {
1544
+ test('validates required fields on submit', async () => {
1545
+ render(<LoginForm />);
1546
+
1547
+ await userEvent.click(screen.getByRole('button', { name: /submit/i }));
1548
+
1549
+ await waitFor(() => {
1550
+ expect(screen.getByText('Email is required')).toBeInTheDocument();
1551
+ expect(screen.getByText('Password is required')).toBeInTheDocument();
1552
+ });
1553
+ });
1554
+
1555
+ test('submits valid form', async () => {
1556
+ const onSubmit = mock((_values: Record<string, string>) => {});
1557
+ render(<LoginForm onSubmit={onSubmit} />);
1558
+
1559
+ await userEvent.type(screen.getByLabelText(/email/i), 'user@example.com');
1560
+ await userEvent.type(screen.getByLabelText(/password/i), 'password123');
1561
+ await userEvent.click(screen.getByRole('button', { name: /submit/i }));
1562
+
1563
+ await waitFor(() => {
1564
+ expect(onSubmit).toHaveBeenCalledWith({
1565
+ email: 'user@example.com',
1566
+ password: 'password123',
1567
+ });
1568
+ });
1569
+ });
1570
+
1571
+ test('displays server errors', async () => {
1572
+ // Mock API that returns a server error
1573
+ global.fetch = mock(() =>
1574
+ Promise.resolve({
1575
+ ok: false,
1576
+ json: () => Promise.resolve({ email: 'Email already exists' }),
1577
+ })
1578
+ ) as typeof fetch;
1579
+
1580
+ render(<RegistrationForm />);
1581
+
1582
+ await userEvent.type(screen.getByLabelText(/email/i), 'taken@example.com');
1583
+ await userEvent.type(screen.getByLabelText(/password/i), 'password123');
1584
+ await userEvent.click(screen.getByRole('button', { name: /register/i }));
1585
+
1586
+ await waitFor(() => {
1587
+ expect(screen.getByText('Email already exists')).toBeInTheDocument();
1588
+ });
1589
+ });
1590
+ });
1591
+ ```
1592
+
1593
+ **Tips:**
1594
+
1595
+ - Test from the user's perspective (type, click, assert on visible text)
1596
+ - Use `waitFor` for async operations (validation, submission)
1597
+ - Mock `fetch` for server error scenarios
1598
+ - Test the `touched && errors` pattern by interacting before asserting
1599
+
1600
+ ---
1601
+
1602
+ ## Form State Persistence
1603
+
1604
+ **Problem:** You want to preserve form state across page reloads (long forms, multi-step wizards).
1605
+
1606
+ **Solution:** Save values to `localStorage` on change, restore on mount.
1607
+
1608
+ ```tsx
1609
+ function PersistentForm() {
1610
+ const saved = JSON.parse(localStorage.getItem('draftForm') || '{}');
1611
+
1612
+ const form = useForm(formSchema, {
1613
+ initialValues: { name: '', email: '', ...saved },
1614
+ onSubmit: async (values) => {
1615
+ await api.submit(values);
1616
+ localStorage.removeItem('draftForm');
1617
+ form.resetForm();
1618
+ },
1619
+ });
1620
+
1621
+ // Save on every change
1622
+ useEffect(() => {
1623
+ localStorage.setItem('draftForm', JSON.stringify(form.values));
1624
+ }, [form.values]);
1625
+
1626
+ return (
1627
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1628
+ <input {...form.getFieldProps('name')} />
1629
+ <input {...form.getFieldProps('email')} />
1630
+ <button type="submit">Submit</button>
1631
+ </form>
1632
+ );
1633
+ }
1634
+ ```
1635
+
1636
+ ---
1637
+
1638
+ ## Unsaved Changes Warning
1639
+
1640
+ **Problem:** Users accidentally navigate away from a dirty form and lose their work.
1641
+
1642
+ **Solution:** Listen for `beforeunload` when the form is dirty.
1643
+
1644
+ ```tsx
1645
+ function FormWithWarning() {
1646
+ const form = useForm(schema, {
1647
+ initialValues: {
1648
+ /* ... */
1649
+ },
1650
+ });
1651
+
1652
+ useEffect(() => {
1653
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
1654
+ if (form.isDirty) {
1655
+ e.preventDefault();
1656
+ e.returnValue = '';
1657
+ }
1658
+ };
1659
+
1660
+ window.addEventListener('beforeunload', handleBeforeUnload);
1661
+ return () => window.removeEventListener('beforeunload', handleBeforeUnload);
1662
+ }, [form.isDirty]);
1663
+
1664
+ return (
1665
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1666
+ {/* fields */}
1667
+ <button type="submit">Save</button>
1668
+ </form>
1669
+ );
1670
+ }
1671
+ ```
1672
+
1673
+ For React Router or Next.js navigation, you'll also need to hook into the router's navigation events (e.g., `useBlocker` in React Router v6).
1674
+
1675
+ ---
1676
+
1677
+ ## Capstone: Full Registration Form (Result Pattern)
1678
+
1679
+ This recipe combines everything: schema validation, per-field async validators, server errors, cross-field validation (password confirmation), and Result pattern-matching on submit.
1680
+
1681
+ ```tsx
1682
+ import { useForm } from '@railway-ts/use-form';
1683
+ import {
1684
+ ok,
1685
+ err,
1686
+ match,
1687
+ fromPromise,
1688
+ type Result,
1689
+ } from '@railway-ts/pipelines/result';
1690
+ import {
1691
+ object,
1692
+ string,
1693
+ required,
1694
+ chain,
1695
+ refineAt,
1696
+ nonEmpty,
1697
+ email,
1698
+ minLength,
1699
+ ROOT_ERROR_KEY,
1700
+ type InferSchemaType,
1701
+ } from '@railway-ts/pipelines/schema';
1702
+
1703
+ // --- Schema ---
1704
+
1705
+ const schema = chain(
1706
+ object({
1707
+ username: required(chain(string(), nonEmpty(), minLength(3))),
1708
+ email: required(chain(string(), nonEmpty(), email())),
1709
+ password: required(chain(string(), nonEmpty(), minLength(8))),
1710
+ confirmPassword: required(chain(string(), nonEmpty())),
1711
+ }),
1712
+ refineAt(
1713
+ 'confirmPassword',
1714
+ (d) => d.password === d.confirmPassword,
1715
+ 'Passwords must match'
1716
+ )
1717
+ );
1718
+
1719
+ type Registration = InferSchemaType<typeof schema>;
1720
+
1721
+ // --- API layer ---
1722
+
1723
+ const checkUsername = (username: string) =>
1724
+ fromPromise<{ available: boolean }>(
1725
+ fetch(`/api/check-username?u=${encodeURIComponent(username)}`).then(
1726
+ (res) => (res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`))
1727
+ )
1728
+ );
1729
+
1730
+ const registerUser = async (
1731
+ values: Registration
1732
+ ): Promise<Result<void, Record<string, string>>> => {
1733
+ const result = await fromPromise(
1734
+ fetch('/api/register', {
1735
+ method: 'POST',
1736
+ headers: { 'Content-Type': 'application/json' },
1737
+ body: JSON.stringify(values),
1738
+ })
1739
+ );
1740
+
1741
+ if (!result.ok)
1742
+ return err({ [ROOT_ERROR_KEY]: 'Network error. Please try again.' });
1743
+
1744
+ const res = result.value;
1745
+ if (!res.ok) return err((await res.json()) as Record<string, string>);
1746
+
1747
+ return ok(undefined);
1748
+ };
1749
+
1750
+ // --- Component ---
1751
+
1752
+ export function RegistrationForm() {
1753
+ const form = useForm<Registration>(schema, {
1754
+ initialValues: {
1755
+ username: '',
1756
+ email: '',
1757
+ password: '',
1758
+ confirmPassword: '',
1759
+ },
1760
+ fieldValidators: {
1761
+ username: async (value) => {
1762
+ const result = await checkUsername(value);
1763
+ return match(result, {
1764
+ ok: ({ available }) =>
1765
+ available ? undefined : 'Username is already taken',
1766
+ err: () => 'Unable to check username availability',
1767
+ });
1768
+ },
1769
+ },
1770
+ onSubmit: async (values) => {
1771
+ const result = await registerUser(values);
1772
+ match(result, {
1773
+ ok: () => {
1774
+ window.location.reassign = '/welcome';
1775
+ },
1776
+ err: (errors) => form.setServerErrors(errors),
1777
+ });
1778
+ },
1779
+ });
1780
+
1781
+ return (
1782
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1783
+ <input {...form.getFieldProps('username')} />
1784
+ {form.validatingFields.username && <span>Checking...</span>}
1785
+ {form.touched.username && form.errors.username && (
1786
+ <span>{form.errors.username}</span>
1787
+ )}
1788
+
1789
+ <input type="email" {...form.getFieldProps('email')} />
1790
+ {form.touched.email && form.errors.email && (
1791
+ <span>{form.errors.email}</span>
1792
+ )}
1793
+
1794
+ <input type="password" {...form.getFieldProps('password')} />
1795
+ {form.touched.password && form.errors.password && (
1796
+ <span>{form.errors.password}</span>
1797
+ )}
1798
+
1799
+ <input type="password" {...form.getFieldProps('confirmPassword')} />
1800
+ {form.touched.confirmPassword && form.errors.confirmPassword && (
1801
+ <span>{form.errors.confirmPassword}</span>
1802
+ )}
1803
+
1804
+ {form.errors[ROOT_ERROR_KEY] && (
1805
+ <span>{form.errors[ROOT_ERROR_KEY]}</span>
1806
+ )}
1807
+
1808
+ <button type="submit" disabled={form.isSubmitting || form.isValidating}>
1809
+ {form.isSubmitting ? 'Registering...' : 'Create Account'}
1810
+ </button>
1811
+ </form>
1812
+ );
1813
+ }
1814
+ ```
1815
+
1816
+ This form demonstrates:
1817
+
1818
+ - **Schema validation** -- `chain` + `nonEmpty` + `email` + `minLength`
1819
+ - **Cross-field validation** -- `refineAt` for password confirmation
1820
+ - **Per-field async validation** -- `fieldValidators` for username availability with `validatingFields` loading state
1821
+ - **Server errors** -- `setServerErrors` from API response, auto-clear on edit
1822
+ - **Result handling** -- `fromPromise` for both API calls, explicit `ok`/`err` for registration, `match` for branching
1823
+ - **React 19 compatibility** -- `(e) => void form.handleSubmit(e)` pattern
1824
+
1825
+ ---
1826
+
1827
+ ## Capstone: Full Registration Form (React Query)
1828
+
1829
+ The same registration form using React Query for server state and React Router for navigation -- no Result types, just idiomatic React patterns.
1830
+
1831
+ ```tsx
1832
+ import { useNavigate } from 'react-router-dom';
1833
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
1834
+ import { useForm } from '@railway-ts/use-form';
1835
+ import {
1836
+ object,
1837
+ string,
1838
+ required,
1839
+ chain,
1840
+ refineAt,
1841
+ nonEmpty,
1842
+ email,
1843
+ minLength,
1844
+ ROOT_ERROR_KEY,
1845
+ type InferSchemaType,
1846
+ } from '@railway-ts/pipelines/schema';
1847
+
1848
+ // --- Schema ---
1849
+
1850
+ const schema = chain(
1851
+ object({
1852
+ username: required(chain(string(), nonEmpty(), minLength(3))),
1853
+ email: required(chain(string(), nonEmpty(), email())),
1854
+ password: required(chain(string(), nonEmpty(), minLength(8))),
1855
+ confirmPassword: required(chain(string(), nonEmpty())),
1856
+ }),
1857
+ refineAt(
1858
+ 'confirmPassword',
1859
+ (d) => d.password === d.confirmPassword,
1860
+ 'Passwords must match'
1861
+ )
1862
+ );
1863
+
1864
+ type Registration = InferSchemaType<typeof schema>;
1865
+
1866
+ // --- API layer ---
1867
+
1868
+ const checkUsername = (username: string): Promise<{ available: boolean }> =>
1869
+ fetch(`/api/check-username?u=${encodeURIComponent(username)}`).then((res) =>
1870
+ res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`)
1871
+ );
1872
+
1873
+ class ApiValidationError extends Error {
1874
+ constructor(public fieldErrors: Record<string, string>) {
1875
+ super('Validation failed');
1876
+ }
1877
+ }
1878
+
1879
+ const registerUser = async (values: Registration): Promise<void> => {
1880
+ const res = await fetch('/api/register', {
1881
+ method: 'POST',
1882
+ headers: { 'Content-Type': 'application/json' },
1883
+ body: JSON.stringify(values),
1884
+ });
1885
+
1886
+ if (!res.ok) throw new ApiValidationError(await res.json());
1887
+ };
1888
+
1889
+ // --- Component ---
1890
+
1891
+ export function RegistrationForm() {
1892
+ const navigate = useNavigate();
1893
+ const queryClient = useQueryClient();
1894
+
1895
+ const mutation = useMutation({
1896
+ mutationFn: registerUser,
1897
+ onSuccess: () => navigate('/welcome'),
1898
+ onError: (error) => {
1899
+ if (error instanceof ApiValidationError) {
1900
+ form.setServerErrors(error.fieldErrors);
1901
+ } else {
1902
+ form.setServerErrors({
1903
+ [ROOT_ERROR_KEY]: 'Network error. Please try again.',
1904
+ });
1905
+ }
1906
+ },
1907
+ });
1908
+
1909
+ const form = useForm<Registration>(schema, {
1910
+ initialValues: {
1911
+ username: '',
1912
+ email: '',
1913
+ password: '',
1914
+ confirmPassword: '',
1915
+ },
1916
+ fieldValidators: {
1917
+ username: async (value) => {
1918
+ try {
1919
+ const { available } = await queryClient.fetchQuery({
1920
+ queryKey: ['check-username', value],
1921
+ queryFn: () => checkUsername(value),
1922
+ staleTime: 30_000,
1923
+ });
1924
+ return available ? undefined : 'Username is already taken';
1925
+ } catch {
1926
+ return 'Unable to check username availability';
1927
+ }
1928
+ },
1929
+ },
1930
+ onSubmit: (values) => mutation.mutate(values),
1931
+ });
1932
+
1933
+ return (
1934
+ <form onSubmit={(e) => void form.handleSubmit(e)}>
1935
+ <input {...form.getFieldProps('username')} />
1936
+ {form.validatingFields.username && <span>Checking...</span>}
1937
+ {form.touched.username && form.errors.username && (
1938
+ <span>{form.errors.username}</span>
1939
+ )}
1940
+
1941
+ <input type="email" {...form.getFieldProps('email')} />
1942
+ {form.touched.email && form.errors.email && (
1943
+ <span>{form.errors.email}</span>
1944
+ )}
1945
+
1946
+ <input type="password" {...form.getFieldProps('password')} />
1947
+ {form.touched.password && form.errors.password && (
1948
+ <span>{form.errors.password}</span>
1949
+ )}
1950
+
1951
+ <input type="password" {...form.getFieldProps('confirmPassword')} />
1952
+ {form.touched.confirmPassword && form.errors.confirmPassword && (
1953
+ <span>{form.errors.confirmPassword}</span>
1954
+ )}
1955
+
1956
+ {form.errors[ROOT_ERROR_KEY] && (
1957
+ <span>{form.errors[ROOT_ERROR_KEY]}</span>
1958
+ )}
1959
+
1960
+ <button type="submit" disabled={mutation.isPending || form.isValidating}>
1961
+ {mutation.isPending ? 'Registering...' : 'Create Account'}
1962
+ </button>
1963
+ </form>
1964
+ );
1965
+ }
1966
+ ```
1967
+
1968
+ This form demonstrates:
1969
+
1970
+ - **Schema validation** -- `chain` + `nonEmpty` + `email` + `minLength`
1971
+ - **Cross-field validation** -- `refineAt` for password confirmation
1972
+ - **Per-field async validation** -- `queryClient.fetchQuery` with `staleTime` for caching username checks
1973
+ - **Server errors** -- `ApiValidationError` + `useMutation` `onError` → `setServerErrors`, auto-clear on edit
1974
+ - **React Query integration** -- `useMutation` for submit, `fetchQuery` for field validation
1975
+ - **React 19 compatibility** -- `(e) => void form.handleSubmit(e)` pattern
1976
+
1977
+ ---
1978
+
1979
+ ## What's Next
1980
+
1981
+ - **[API Reference](./API.md)** -- Complete API documentation