@railway-ts/use-form 0.1.24 → 0.1.26

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.
package/docs/API.md CHANGED
@@ -208,7 +208,7 @@ form.touched.password; // false
208
208
 
209
209
  Type: `Record<FieldPath, string>`
210
210
 
211
- Combined client and server errors. Server errors take precedence.
211
+ Combined client, field validator, and server errors. Server errors take highest precedence (server > field > client).
212
212
 
213
213
  ```typescript
214
214
  form.errors.email; // "Email is required"
@@ -591,7 +591,7 @@ getFieldId<TField extends ExtractFieldPaths<TValues>>(
591
591
  Manually trigger validation.
592
592
 
593
593
  ```typescript
594
- validateForm(values: TValues): Result<TValues, ValidationError[]>
594
+ validateForm(values: TValues): Result<TValues, ValidationError[]> | Promise<Result<TValues, ValidationError[]>>
595
595
  ```
596
596
 
597
597
  **Parameters:**
@@ -599,7 +599,7 @@ validateForm(values: TValues): Result<TValues, ValidationError[]>
599
599
  - `values` - Values to validate
600
600
 
601
601
  **Returns:**
602
- Railway Result type with validated data or errors.
602
+ Railway Result type with validated data or errors. Returns a Promise when using an async validator.
603
603
 
604
604
  **Example:**
605
605
 
@@ -751,6 +751,7 @@ getSliderProps<TField extends ExtractFieldPaths<TValues>>(
751
751
  {
752
752
  id: string;
753
753
  name: string;
754
+ type: 'range';
754
755
  value: number;
755
756
  onChange: (e: ChangeEvent<HTMLInputElement>) => void;
756
757
  onBlur: () => void;
@@ -972,20 +973,6 @@ swap(indexA: number, indexB: number): void
972
973
  helpers.swap(0, 2); // Swap first and third items
973
974
  ```
974
975
 
975
- #### move
976
-
977
- Move item from one position to another.
978
-
979
- ```typescript
980
- move(from: number, to: number): void
981
- ```
982
-
983
- **Example:**
984
-
985
- ```typescript
986
- helpers.move(2, 0); // Move third item to first position
987
- ```
988
-
989
976
  #### replace
990
977
 
991
978
  Replace item at index.
@@ -1130,6 +1117,46 @@ getRadioGroupOptionProps<TField extends ExtractFieldPaths<TItem>>(
1130
1117
  />
1131
1118
  ```
1132
1119
 
1120
+ #### getFieldError
1121
+
1122
+ Get validation error for item field.
1123
+
1124
+ ```typescript
1125
+ getFieldError<TField extends ExtractFieldPaths<TItem>>(
1126
+ index: number,
1127
+ field: TField
1128
+ ): string | undefined
1129
+ ```
1130
+
1131
+ **Example:**
1132
+
1133
+ ```tsx
1134
+ {
1135
+ helpers.getFieldError(0, 'name') && (
1136
+ <span>{helpers.getFieldError(0, 'name')}</span>
1137
+ );
1138
+ }
1139
+ ```
1140
+
1141
+ #### getFieldId
1142
+
1143
+ Get a stable HTML element ID for an item field. Useful for `<label htmlFor>`.
1144
+
1145
+ ```typescript
1146
+ getFieldId<TField extends ExtractFieldPaths<TItem>>(
1147
+ index: number,
1148
+ field: TField,
1149
+ optionValue?: string | number
1150
+ ): string
1151
+ ```
1152
+
1153
+ **Example:**
1154
+
1155
+ ```tsx
1156
+ <label htmlFor={helpers.getFieldId(index, "name")}>Name</label>
1157
+ <input {...helpers.getFieldProps(index, "name")} />
1158
+ ```
1159
+
1133
1160
  ## useFormAutoSubmission
1134
1161
 
1135
1162
  Hook for auto-submitting forms after debounced changes.
@@ -1270,6 +1297,8 @@ const accountValidator = chain(
1270
1297
  );
1271
1298
  ```
1272
1299
 
1300
+ > **Tip:** For multiple conditional fields, consider [`when`](#when) for a more readable approach.
1301
+
1273
1302
  **Example:**
1274
1303
 
1275
1304
  ```typescript
@@ -1289,6 +1318,90 @@ const bookingValidator = chain(
1289
1318
 
1290
1319
  **See also:** [Recipes - Dependent Fields](./RECIPES.md#dependent-fields--cross-field-validation) for more examples
1291
1320
 
1321
+ ### when
1322
+
1323
+ Conditionally apply validators based on a runtime predicate. When the predicate returns `true`, `thenValidator` runs. When `false`, `elseValidator` runs (if provided), otherwise the value passes through unchanged.
1324
+
1325
+ ```typescript
1326
+ function when<T>(
1327
+ predicate: (data: T) => boolean,
1328
+ thenValidator: Validator<T, T>,
1329
+ elseValidator?: Validator<T, T>,
1330
+ ): Validator<T, T>;
1331
+ ```
1332
+
1333
+ **Parameters:**
1334
+
1335
+ - `predicate` - Function receiving the entire object, returns `true` to apply `thenValidator`
1336
+ - `thenValidator` - Validator applied when predicate returns `true`
1337
+ - `elseValidator` - Optional validator applied when predicate returns `false`
1338
+
1339
+ **Returns:** Validator function for use with `chain` at object level
1340
+
1341
+ **Example:**
1342
+
1343
+ ```typescript
1344
+ import { chain, object, required, optional, string, stringEnum, refineAt, when, type InferSchemaType } from '@railway-ts/pipelines/schema';
1345
+
1346
+ const baseSchema = object({
1347
+ accountType: required(stringEnum(['personal', 'business'])),
1348
+ companyName: optional(string()),
1349
+ taxId: optional(string()),
1350
+ });
1351
+
1352
+ type AccountData = InferSchemaType<typeof baseSchema>;
1353
+
1354
+ const accountValidator = chain(
1355
+ baseSchema,
1356
+ when<AccountData>(
1357
+ (d) => d.accountType === 'business',
1358
+ chain(
1359
+ refineAt('companyName', (d) => !!d.companyName, 'Company name is required for business accounts'),
1360
+ refineAt('taxId', (d) => !!d.taxId, 'Tax ID is required for business accounts'),
1361
+ ),
1362
+ ),
1363
+ );
1364
+ ```
1365
+
1366
+ **See also:** [Recipes - Conditional Validation](./RECIPES.md#conditional-validation) for a full React example
1367
+
1368
+ ### whenAsync
1369
+
1370
+ Async version of `when`. Use when the branch validators involve async operations (database checks, API calls, etc.).
1371
+
1372
+ ```typescript
1373
+ function whenAsync<T>(
1374
+ predicate: (data: T) => boolean,
1375
+ thenValidator: MaybeAsyncValidator<T, T>,
1376
+ elseValidator?: MaybeAsyncValidator<T, T>,
1377
+ ): AsyncValidator<T, T>;
1378
+ ```
1379
+
1380
+ **Parameters:**
1381
+
1382
+ - `predicate` - Function receiving the entire object, returns `true` to apply `thenValidator`
1383
+ - `thenValidator` - Sync or async validator applied when predicate returns `true`
1384
+ - `elseValidator` - Optional sync or async validator applied when predicate returns `false`
1385
+
1386
+ **Returns:** Async validator function for use with `chainAsync` at object level
1387
+
1388
+ **Example:**
1389
+
1390
+ ```typescript
1391
+ import { chainAsync, object, required, optional, string, stringEnum, refineAtAsync, whenAsync } from '@railway-ts/pipelines/schema';
1392
+
1393
+ const staffValidator = chainAsync(
1394
+ object({
1395
+ role: required(stringEnum(['admin', 'doctor', 'nurse'])),
1396
+ license: optional(string()),
1397
+ }),
1398
+ whenAsync<StaffData>(
1399
+ (d) => d.role === 'doctor',
1400
+ refineAtAsync('license', async (d) => await verifyMedicalLicense(d.license), 'Invalid medical license'),
1401
+ ),
1402
+ );
1403
+ ```
1404
+
1292
1405
  ### Validation Paths
1293
1406
 
1294
1407
  There are two patterns for where validation errors land:
@@ -1301,7 +1414,7 @@ There are two patterns for where validation errors land:
1301
1414
 
1302
1415
  **Cross-field validation** -- validating based on other fields:
1303
1416
 
1304
- - Use `chain` at the **object level** with `refineAt`
1417
+ - Use `chain` at the **object level** with `refineAt` or `when`
1305
1418
  - The first argument to `refineAt` is the field path where the error should appear
1306
1419
  - The predicate receives the entire parent object
1307
1420
  - Example: `refineAt('confirmPassword', (data) => data.password === data.confirmPassword, '...')`
@@ -328,7 +328,7 @@ The field path autocomplete works through nested objects -- type `'address.'` an
328
328
 
329
329
  ## Step 7: Arrays
330
330
 
331
- Use `arrayHelpers` for dynamic lists. It gives you `push`, `remove`, `swap`, `move`, `insert`, `replace`, and its own `getFieldProps` that takes an index:
331
+ Use `arrayHelpers` for dynamic lists. It gives you `push`, `remove`, `swap`, `insert`, `replace`, and its own `getFieldProps` that takes an index:
332
332
 
333
333
  ```tsx
334
334
  import {
@@ -365,16 +365,16 @@ function ContactsForm() {
365
365
  <h3>Contact {index + 1}</h3>
366
366
 
367
367
  <input {...helpers.getFieldProps(index, 'name')} placeholder="Name" />
368
- {form.getFieldError(`contacts.${index}.name`) && (
369
- <span>{form.getFieldError(`contacts.${index}.name`)}</span>
368
+ {helpers.getFieldError(index, 'name') && (
369
+ <span>{helpers.getFieldError(index, 'name')}</span>
370
370
  )}
371
371
 
372
372
  <input
373
373
  {...helpers.getFieldProps(index, 'email')}
374
374
  placeholder="Email"
375
375
  />
376
- {form.getFieldError(`contacts.${index}.email`) && (
377
- <span>{form.getFieldError(`contacts.${index}.email`)}</span>
376
+ {helpers.getFieldError(index, 'email') && (
377
+ <span>{helpers.getFieldError(index, 'email')}</span>
378
378
  )}
379
379
 
380
380
  <button type="button" onClick={() => helpers.remove(index)}>
@@ -400,15 +400,23 @@ Array helpers provide full type safety -- `helpers.getFieldProps(index, 'name')`
400
400
 
401
401
  **All array operations:**
402
402
 
403
- | Method | What it does |
404
- | ----------------------------- | ------------------------- |
405
- | `push(item)` | Add to end |
406
- | `remove(index)` | Remove by index |
407
- | `insert(index, item)` | Insert at position |
408
- | `swap(indexA, indexB)` | Swap two items |
409
- | `move(from, to)` | Move item to new position |
410
- | `replace(index, item)` | Replace item at index |
411
- | `getFieldProps(index, field)` | Get props for item field |
403
+ | Member | What it does |
404
+ | ----------------------------------------------- | ------------------------------------- |
405
+ | `values` | Current array items |
406
+ | `push(item)` | Add to end |
407
+ | `remove(index)` | Remove by index |
408
+ | `insert(index, item)` | Insert at position |
409
+ | `swap(indexA, indexB)` | Swap two items |
410
+ | `replace(index, item)` | Replace item at index |
411
+ | `getFieldProps(index, field)` | Get text/number input props |
412
+ | `getSelectFieldProps(index, field)` | Get select element props |
413
+ | `getSliderProps(index, field)` | Get range input props |
414
+ | `getCheckboxProps(index, field)` | Get checkbox input props |
415
+ | `getSwitchProps(index, field)` | Get switch/toggle props |
416
+ | `getFileFieldProps(index, field)` | Get file input props |
417
+ | `getRadioGroupOptionProps(index, field, value)` | Get radio button props |
418
+ | `getFieldError(index, field)` | Get error for item field |
419
+ | `getFieldId(index, field, optionValue?)` | Get unique ID for labels/accessibility|
412
420
 
413
421
  ---
414
422
 
package/docs/RECIPES.md CHANGED
@@ -204,6 +204,7 @@ const todosSchema = object({
204
204
  object({
205
205
  text: required(chain(string(), nonEmpty('Task is required'))),
206
206
  done: required(boolean()),
207
+ priority: required(stringEnum(['low', 'medium', 'high'])),
207
208
  })
208
209
  ),
209
210
  });
@@ -223,6 +224,15 @@ function TodoList() {
223
224
  <div key={index}>
224
225
  <input type="checkbox" {...helpers.getCheckboxProps(index, 'done')} />
225
226
  <input {...helpers.getFieldProps(index, 'text')} />
227
+ {helpers.getFieldError(index, 'text') && (
228
+ <span>{helpers.getFieldError(index, 'text')}</span>
229
+ )}
230
+
231
+ <select {...helpers.getSelectFieldProps(index, 'priority')}>
232
+ <option value="low">Low</option>
233
+ <option value="medium">Medium</option>
234
+ <option value="high">High</option>
235
+ </select>
226
236
 
227
237
  <button
228
238
  onClick={() => index > 0 && helpers.swap(index, index - 1)}
@@ -243,7 +253,11 @@ function TodoList() {
243
253
  </div>
244
254
  ))}
245
255
 
246
- <button onClick={() => helpers.push({ text: '', done: false })}>
256
+ <button
257
+ onClick={() =>
258
+ helpers.push({ text: '', done: false, priority: 'medium' })
259
+ }
260
+ >
247
261
  Add Todo
248
262
  </button>
249
263
  </div>
@@ -256,8 +270,8 @@ function TodoList() {
256
270
  ```typescript
257
271
  // Add multiple items
258
272
  const newTasks = [
259
- { text: 'Task 1', done: false },
260
- { text: 'Task 2', done: false },
273
+ { text: 'Task 1', done: false, priority: 'medium' as const },
274
+ { text: 'Task 2', done: false, priority: 'medium' as const },
261
275
  ];
262
276
  newTasks.forEach((task) => helpers.push(task));
263
277
 
@@ -347,7 +361,7 @@ import { chain, refine } from '@railway-ts/pipelines/schema';
347
361
  const fileValidator = chain(
348
362
  refine<File>((value) => value instanceof File, 'Must be a file'),
349
363
  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'),
364
+ refine<File>((value) => value.type.startsWith('image/'), 'Must be an image')
351
365
  );
352
366
 
353
367
  const uploadSchema = object({
@@ -602,35 +616,47 @@ The key insight: `chain` at the **object level** (not the field level) gives `re
602
616
 
603
617
  **Problem:** Some fields are only required based on another field's value -- like company name and tax ID for business accounts.
604
618
 
605
- **Solution:** Same technique as cross-field validation. Use `refineAt` to conditionally require fields.
619
+ **Solution:** Use `when` from `@railway-ts/pipelines/schema` to branch validation based on a runtime predicate. The `then` validator runs when the predicate returns true; the value passes through unchanged otherwise.
606
620
 
607
621
  ```tsx
622
+ import {
623
+ object,
624
+ string,
625
+ required,
626
+ optional,
627
+ chain,
628
+ refineAt,
629
+ stringEnum,
630
+ when,
631
+ type InferSchemaType,
632
+ } from '@railway-ts/pipelines/schema';
633
+ import { useForm } from '@railway-ts/use-form';
634
+
635
+ const baseSchema = object({
636
+ accountType: required(stringEnum(['personal', 'business'])),
637
+ companyName: optional(string()),
638
+ taxId: optional(string()),
639
+ });
640
+
641
+ type AccountData = InferSchemaType<typeof baseSchema>;
642
+
608
643
  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'
644
+ baseSchema,
645
+ when<AccountData>(
646
+ (d) => d.accountType === 'business',
647
+ chain(
648
+ refineAt('companyName', (d) => !!d.companyName, 'Company name is required for business accounts'),
649
+ refineAt('taxId', (d) => !!d.taxId, 'Tax ID is required for business accounts'),
650
+ ),
618
651
  ),
619
- refineAt(
620
- 'taxId',
621
- (data) => data.accountType === 'personal' || !!data.taxId,
622
- 'Tax ID is required for business accounts'
623
- )
624
652
  );
625
653
 
626
- type AccountData = InferSchemaType<typeof accountSchema>;
627
-
628
654
  function AccountForm() {
629
655
  const form = useForm<AccountData>(accountSchema, {
630
656
  initialValues: { accountType: 'personal', companyName: '', taxId: '' },
631
657
  });
632
658
 
633
- const isBusiness = form.values.accountType === 'business';
659
+ const isBiz = form.values.accountType === 'business';
634
660
 
635
661
  return (
636
662
  <form onSubmit={(e) => void form.handleSubmit(e)}>
@@ -639,7 +665,7 @@ function AccountForm() {
639
665
  <option value="business">Business</option>
640
666
  </select>
641
667
 
642
- {isBusiness && (
668
+ {isBiz && (
643
669
  <>
644
670
  <input
645
671
  {...form.getFieldProps('companyName')}
@@ -662,6 +688,22 @@ function AccountForm() {
662
688
  }
663
689
  ```
664
690
 
691
+ Each `refineAt` inside `when` only checks its own field — the `when` wrapper already gates execution to business accounts. For async conditional checks, use `whenAsync` with `chainAsync`:
692
+
693
+ ```typescript
694
+ import { chainAsync, whenAsync, refineAtAsync } from '@railway-ts/pipelines/schema';
695
+
696
+ const staffSchema = chainAsync(
697
+ baseStaffSchema,
698
+ whenAsync<StaffData>(
699
+ (d) => d.role === 'doctor',
700
+ refineAtAsync('license', async (d) => await verifyMedicalLicense(d.license), 'Invalid medical license'),
701
+ ),
702
+ );
703
+ ```
704
+
705
+ > **Note:** For simple single-field conditionals, chaining `refineAt` with an inverted predicate still works — see [Dependent Fields](#dependent-fields--cross-field-validation). `when` shines when you have multiple conditional fields or want the intent to read top-to-bottom without inverted logic.
706
+
665
707
  ---
666
708
 
667
709
  ## Discriminated Unions
@@ -1195,7 +1237,11 @@ match(result, {
1195
1237
  **Solution:** Extract a reusable `Field` component that takes the form instance, field name, and label.
1196
1238
 
1197
1239
  ```tsx
1198
- import { useForm, type UseFormReturn, type ExtractFieldPaths } from '@railway-ts/use-form';
1240
+ import {
1241
+ useForm,
1242
+ type UseFormReturn,
1243
+ type ExtractFieldPaths,
1244
+ } from '@railway-ts/use-form';
1199
1245
  import {
1200
1246
  object,
1201
1247
  required,
@@ -1262,7 +1308,11 @@ Wrap field components in `React.memo` so they only re-render when their specific
1262
1308
 
1263
1309
  ```tsx
1264
1310
  import { memo, useMemo } from 'react';
1265
- import { useForm, type UseFormReturn, type ExtractFieldPaths } from '@railway-ts/use-form';
1311
+ import {
1312
+ useForm,
1313
+ type UseFormReturn,
1314
+ type ExtractFieldPaths,
1315
+ } from '@railway-ts/use-form';
1266
1316
  import {
1267
1317
  object,
1268
1318
  required,
@@ -1507,7 +1557,9 @@ function ShadcnForm() {
1507
1557
  <Label htmlFor={form.getFieldId('email')}>Email</Label>
1508
1558
  <Input {...form.getFieldProps('email')} />
1509
1559
  {form.getFieldError('email') && (
1510
- <p className="text-sm text-destructive">{form.getFieldError('email')}</p>
1560
+ <p className="text-sm text-destructive">
1561
+ {form.getFieldError('email')}
1562
+ </p>
1511
1563
  )}
1512
1564
  </div>
1513
1565
 
@@ -1515,7 +1567,9 @@ function ShadcnForm() {
1515
1567
  <Label htmlFor={form.getFieldId('password')}>Password</Label>
1516
1568
  <Input type="password" {...form.getFieldProps('password')} />
1517
1569
  {form.getFieldError('password') && (
1518
- <p className="text-sm text-destructive">{form.getFieldError('password')}</p>
1570
+ <p className="text-sm text-destructive">
1571
+ {form.getFieldError('password')}
1572
+ </p>
1519
1573
  )}
1520
1574
  </div>
1521
1575
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@railway-ts/use-form",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "React form hook that works with @railway-ts/pipelines to manage form state, validation, and submission.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -71,13 +71,13 @@
71
71
  }
72
72
  ],
73
73
  "peerDependencies": {
74
- "@railway-ts/pipelines": "^0.1.25",
74
+ "@railway-ts/pipelines": "^0.1.26",
75
75
  "react": "^18.0.0 || ^19.0.0",
76
76
  "typescript": "^5"
77
77
  },
78
78
  "devDependencies": {
79
79
  "@happy-dom/global-registrator": "^20.0.10",
80
- "@railway-ts/pipelines": "^0.1.25",
80
+ "@railway-ts/pipelines": "^0.1.26",
81
81
  "@testing-library/dom": "^10.4.1",
82
82
  "@testing-library/jest-dom": "^6.9.1",
83
83
  "@testing-library/react": "^16.3.0",