Open History to see the last commit
1import { describe, expect, expectTypeOf, it, vi } from 'vitest'
2import { z } from 'zod'
3import {
4 runFieldValidatorPipeline,
5 runFormValidatorPipeline,
6} from '../src/validation'
7import { InternalFormApi } from '../src/FormApi/FormApi.lib'
8import { reconcileValidatorInstances } from '../src/ValidatorInstance.lib'
9import type { PipelineResult } from '../src/validation'
10import type {
11 ClientValidationTrigger,
12 DeepKeys,
13 DeepValue,
14 FieldValidateResult,
15 FieldValidator,
16 FormValidateResult,
17 FormValidator,
18 FormValidatorContext,
19 ToFormOutputs,
20 ValidationDebounceFn,
21 ValidationPredicateFn,
22} from '../src'
23import type { AnyInternalFieldApi } from '../src/FieldApi/FieldApi.lib'
24import type { StandardSchemaV1 } from '../src/standardSchema.public'
25β
26describe('runFormValidatorPipeline', () => {
27 type Event = Exclude<FormValidatorContext<any>['event'], 'server'>
28β
29 function getForm<T>(defaultValues: T) {
30 return new InternalFormApi({ defaultValues })
31 }
32β
33 function getPipeline<T>(
34 form: InternalFormApi<T, any, any>,
35 pipeline: Array<FormValidator<T>>,
36 ) {
37 const validatorInstances = reconcileValidatorInstances({
38 definitions: pipeline,
39 instances: null,
40 owner: form,
41 scope: 'form',
42 })!
43 return {
44 pipeline: validatorInstances,
45 runWithContext: (args: {
46 event: Event
47 field?: AnyInternalFieldApi
48 onResult?: (result: PipelineResult<FormValidateResult<any>>) => void
49 hasFailedBefore?: boolean
50 }) => {
51 return runFormValidatorPipeline({
52 context: {
53 scope: 'form',
54 event: args.event,
55 formApi: form,
56 triggerFieldApi: args.field,
57 },
58 hasFailedBefore: args.hasFailedBefore ?? false,
59 onResult: args.onResult,
60 pipeline: validatorInstances,
61 }).then((res) => res.results)
62 },
63 }
64 }
65β
66 function getFieldPipeline<
67 TFormData,
68 TFieldName extends DeepKeys<TFormData>,
69 TFieldValue extends DeepValue<TFormData, TFieldName>,
70 >(
71 form: InternalFormApi<TFormData, any, any>,
72 field: AnyInternalFieldApi,
73 pipeline: Array<FieldValidator<TFormData, TFieldName, TFieldValue>>,
74 ) {
75 const validatorInstances = reconcileValidatorInstances({
76 definitions: pipeline,
77 instances: null,
78 owner: field,
79 scope: 'field',
80 })!
81 return {
82 pipeline: validatorInstances,
83 runWithContext: (args: {
84 event: ClientValidationTrigger
85 onResult?: (result: PipelineResult<FieldValidateResult>) => void
86 }) => {
87 return runFieldValidatorPipeline({
88 context: {
89 scope: 'field',
90 event: args.event,
91 formApi: form,
92 fieldApi: field,
93 },
94 onResult: args.onResult,
95 pipeline: validatorInstances,
96 }).then((res) => res.results)
97 },
98 }
99 }
100β
101 it('should run the pipeline with appropriate defaults', async () => {
102 const formApi = getForm({ name: '' })
103 const { runWithContext } = getPipeline(formApi, [
104 {
105 run: () => ({ message: 'foo' }),
106 triggers: [],
107 },
108 ])
109 const results = await runWithContext({ event: 'submit' })
110 expect(results).toHaveLength(1)
111 expect(results).toContainEqual(
112 expect.objectContaining({
113 result: { message: 'foo' },
114 output: null,
115 }),
116 )
117 })
118β
119 it('should preserve form-owned data for form validation contexts', async () => {
120 const formApi = getForm({ users: [{ name: 'test' }] })
121 const field = formApi._getOrCreateFieldApi({ name: 'users[0].name' })
122 const issues = [
123 { message: 'Invalid name', path: ['users', 0, 'name'] as const },
124 ]
125 const run = vi.fn(({ triggerFieldApi, value, parseIssues }) => {
126 expect(triggerFieldApi).toBe(field)
127 expect(value).toBe(formApi.state.values)
128 expect(parseIssues(issues)).toEqual({
129 form: issues,
130 fields: { 'users[0].name': issues },
131 })
132 return null
133 })
134 const { runWithContext } = getPipeline(formApi, [
135 { run, triggers: ['change'] },
136 ])
137β
138 await runWithContext({ event: 'change', field })
139β
140 expect(run).toHaveBeenCalledOnce()
141 })
142β
143 it('should preserve form-owned data for field validation contexts', async () => {
144 const formApi = getForm({ users: [{ name: 'test' }] })
145 const field = formApi._getOrCreateFieldApi({ name: 'users[0].name' })
146 const issues = [
147 { message: 'Invalid name', path: ['users', 0, 'name'] as const },
148 ]
149 const run = vi.fn((context) => {
150 const fieldContext = context as typeof context & {
151 fieldApi: AnyInternalFieldApi
152 }
153β
154 expect(fieldContext.fieldApi).toBe(field)
155 expect(fieldContext).not.toHaveProperty('triggerFieldApi')
156 expect(fieldContext.value).toBe(formApi.state.values)
157 expect(fieldContext.parseIssues(issues)).toEqual({
158 form: issues,
159 fields: { 'users[0].name': issues },
160 })
161 return null
162 })
163 const { pipeline } = getPipeline(formApi, [{ run, triggers: ['change'] }])
164β
165 await runFormValidatorPipeline({
166 context: {
167 scope: 'field',
168 event: 'change',
169 formApi,
170 fieldApi: field,
171 } as never,
172 hasFailedBefore: false,
173 pipeline,
174 })
175β
176 expect(run).toHaveBeenCalledOnce()
177 })
178β
179 it('should provide error map helpers to form validators', async () => {
180 const formApi = getForm({ name: '' })
181 const { runWithContext } = getPipeline(formApi, [
182 {
183 run: ({ createErrorMap }) => {
184 const errors = createErrorMap()
185 errors.fields.name = 'Name is required'
186 return errors
187 },
188 triggers: [],
189 },
190 ])
191β
192 const results = await runWithContext({ event: 'submit' })
193β
194 expect(results).toEqual([
195 expect.objectContaining({
196 result: { fields: { name: 'Name is required' } },
197 }),
198 ])
199 })
200β
201 it('should normalize returned error map helpers', async () => {
202 const formApi = new InternalFormApi({
203 defaultValues: { name: '' },
204 validators: [
205 {
206 run: ({ createErrorMap }) => {
207 const errors = createErrorMap()
208 errors.fields.name = undefined
209 return errors
210 },
211 triggers: [],
212 },
213 ],
214 })
215β
216 const result = await formApi.validate('submit')
217β
218 expect(result).toEqual([])
219 expect(formApi.state.errors).toEqual([])
220 expect(formApi.state.canSubmit).toBe(true)
221 })
222β
223 it('should route errors from returned error map helpers', async () => {
224 const formApi = new InternalFormApi({
225 defaultValues: { name: '' },
226 validators: [
227 {
228 run: ({ createErrorMap }) => {
229 const errors = createErrorMap()
230 errors.fields.name = 'Name is required'
231 return errors
232 },
233 triggers: [],
234 },
235 ],
236 })
237 const field = formApi._getOrCreateFieldApi({ name: 'name' })
238β
239 await formApi.validate('submit')
240β
241 expect(field.errors).toEqual([{ message: 'Name is required' }])
242 })
243β
244 it('should keep plain empty objects as validation errors', async () => {
245 const formApi = new InternalFormApi({
246 defaultValues: { name: '' },
247 validators: [
248 {
249 run: () => ({}) as any,
250 triggers: [],
251 },
252 ],
253 })
254β
255 const result = await formApi.validate('submit')
256β
257 expect(result).toEqual([{}])
258 expect(formApi.state.errors).toEqual([{}])
259 expect(formApi.state.canSubmit).toBe(false)
260 })
261β
262 it('should only run validators with matching signal', async () => {
263 const formApi = getForm({ name: '' })
264β
265 const change = vi.fn()
266 const blur = vi.fn()
267 const blurOrChange = vi.fn()
268β
269 const { runWithContext } = getPipeline(formApi, [
270 {
271 run: change,
272 triggers: ['change'],
273 },
274 {
275 run: blur,
276 triggers: ['blur'],
277 },
278 {
279 run: blurOrChange,
280 triggers: ['blur', 'change'],
281 },
282 ])
283β
284 await runWithContext({ event: 'change' })
285 expect(change).toHaveBeenCalledOnce()
286 expect(blurOrChange).toHaveBeenCalledOnce()
287β
288 expect(blur).not.toHaveBeenCalled()
289β
290 await runWithContext({ event: 'blur' })
291 expect(blur).toHaveBeenCalledOnce()
292β
293 expect(change).toHaveBeenCalledOnce()
294 expect(blurOrChange).toHaveBeenCalledTimes(2)
295 })
296β
297 it('should only run validators on submit if enabled', async () => {
298 const formApi = getForm({ name: '' })
299β
300 const trueByDefault = vi.fn()
301 const trueCallback = vi.fn()
302 const trueBoolean = vi.fn()
303β
304 const falseBoolean = vi.fn()
305 const falseCallback = vi.fn()
306β
307 const { runWithContext } = getPipeline(formApi, [
308 {
309 run: trueByDefault,
310 triggers: [],
311 },
312 {
313 run: trueCallback,
314 skipOnSubmit: () => false,
315 triggers: [],
316 },
317 {
318 run: trueBoolean,
319 skipOnSubmit: false,
320 triggers: [],
321 },
322 {
323 run: falseBoolean,
324 skipOnSubmit: true,
325 triggers: [],
326 },
327 {
328 run: falseCallback,
329 skipOnSubmit: () => true,
330 triggers: [],
331 },
332 ])
333β
334 await runWithContext({ event: 'change' })
335 await runWithContext({ event: 'blur' })
336 expect(trueByDefault).not.toHaveBeenCalled()
337 expect(trueCallback).not.toHaveBeenCalled()
338 expect(trueBoolean).not.toHaveBeenCalled()
339β
340 expect(falseBoolean).not.toHaveBeenCalled()
341 expect(falseCallback).not.toHaveBeenCalled()
342β
343 await runWithContext({ event: 'submit' })
344 expect(trueByDefault).toHaveBeenCalledOnce()
345 expect(trueCallback).toHaveBeenCalledOnce()
346 expect(trueBoolean).toHaveBeenCalledOnce()
347β
348 expect(falseBoolean).not.toHaveBeenCalled()
349 expect(falseCallback).not.toHaveBeenCalled()
350 })
351β
352 it('should debounce non-submit validation', async () => {
353 vi.useFakeTimers()
354β
355 const formApi = getForm({ name: '' })
356 const run = vi.fn(() => ({ message: 'foo' }))
357β
358 const { runWithContext } = getPipeline(formApi, [
359 {
360 run,
361 triggers: ['change'],
362 triggerDebounceMs: 100,
363 },
364 ])
365β
366 const promise = runWithContext({ event: 'change' })
367β
368 expect(run).not.toHaveBeenCalled()
369β
370 await vi.advanceTimersByTimeAsync(99)
371 expect(run).not.toHaveBeenCalled()
372β
373 await vi.advanceTimersByTimeAsync(1)
374β
375 await expect(promise).resolves.toHaveLength(1)
376β
377 expect(run).toHaveBeenCalledOnce()
378 })
379β
380 it('should settle as aborted when a disposed validator cannot create a debouncer', async () => {
381 const formApi = getForm({ name: '' })
382 const run = vi.fn(() => ({ message: 'foo' }))
383 const onResult = vi.fn()
384 const { pipeline, runWithContext } = getPipeline(formApi, [
385 {
386 run,
387 triggers: ['change'],
388 triggerDebounceMs: 100,
389 },
390 ])
391β
392 pipeline[0]!.dispose()
393β
394 await expect(
395 runWithContext({ event: 'change', onResult }),
396 ).resolves.toEqual([])
397 expect(run).not.toHaveBeenCalled()
398 expect(onResult).not.toHaveBeenCalled()
399 })
400β
401 it('should debounce validation with a function', async () => {
402 vi.useFakeTimers()
403β
404 const form = getForm({ name: 'test' })
405 const field = form._getOrCreateFieldApi({ name: 'name' })
406 const run = vi.fn(() => ({ message: 'foo' }))
407 const triggerDebounceMs = vi.fn(({ scope, formApi, fieldApi, value }) => {
408 expect(scope).toBe('form')
409 expect(formApi.state.values).toEqual({ name: 'test' })
410 expect(fieldApi).toBe(field)
411 expect(value).toEqual({ name: 'test' })
412β
413 return 100
414 })
415β
416 const { runWithContext } = getPipeline(form, [
417 {
418 run,
419 triggers: ['change'],
420 triggerDebounceMs,
421 },
422 ])
423β
424 const promise = runWithContext({ event: 'change', field })
425β
426 expect(triggerDebounceMs).toHaveBeenCalledOnce()
427 expect(run).not.toHaveBeenCalled()
428β
429 await vi.advanceTimersByTimeAsync(99)
430 expect(run).not.toHaveBeenCalled()
431β
432 await vi.advanceTimersByTimeAsync(1)
433β
434 await expect(promise).resolves.toHaveLength(1)
435β
436 expect(run).toHaveBeenCalledOnce()
437 })
438β
439 it('should use field value for field-level debounce functions', async () => {
440 vi.useFakeTimers()
441β
442 const formApi = getForm({ name: 'test' })
443 const field = formApi._getOrCreateFieldApi({ name: 'name' })
444 const run = vi.fn(() => ({ message: 'foo' }))
445 const triggerDebounceMs: ValidationDebounceFn<{ name: string }, string> =
446 vi.fn(({ value }) => {
447 expect(value).toBe('test')
448β
449 return value.length * 20
450 })
451 const pipeline: Array<FieldValidator<{ name: string }, 'name', string>> = [
452 {
453 run,
454 triggers: ['change'],
455 triggerDebounceMs,
456 },
457 ]
458β
459 const { runWithContext } = getFieldPipeline(formApi, field, pipeline)
460β
461 const promise = runWithContext({ event: 'change' })
462β
463 expect(triggerDebounceMs).toHaveBeenCalledOnce()
464 expect(run).not.toHaveBeenCalled()
465β
466 await vi.advanceTimersByTimeAsync(79)
467 expect(run).not.toHaveBeenCalled()
468β
469 await vi.advanceTimersByTimeAsync(21)
470β
471 await expect(promise).resolves.toHaveLength(1)
472β
473 expect(run).toHaveBeenCalledOnce()
474 })
475β
476 it('should cancel an existing debounced validation when the same validator runs immediately', async () => {
477 vi.useFakeTimers()
478β
479 const formApi = getForm({ name: '' })
480 const run = vi.fn(() => ({ message: 'foo' }))
481 const onResult = vi.fn()
482β
483 const { runWithContext } = getPipeline(formApi, [
484 {
485 run,
486 triggers: ['change'],
487 triggerDebounceMs: 100,
488 },
489 ])
490β
491 runWithContext({ event: 'change', onResult })
492β
493 await vi.advanceTimersByTimeAsync(50)
494β
495 const submitResults = await runWithContext({ event: 'submit', onResult })
496β
497 expect(run).toHaveBeenCalledOnce()
498 expect(submitResults).toHaveLength(1)
499β
500 expect(onResult).toHaveBeenCalledOnce()
501 expect(onResult).toHaveBeenCalledWith(
502 expect.objectContaining({
503 result: { message: 'foo' },
504 }),
505 )
506β
507 await vi.advanceTimersByTimeAsync(100)
508β
509 expect(run).toHaveBeenCalledOnce()
510 })
511β
512 it('should debounce separate validators independently', async () => {
513 vi.useFakeTimers()
514β
515 const formApi = getForm({ name: '' })
516β
517 const first = vi.fn(() => ({ message: 'first' }))
518 const second = vi.fn(() => ({ message: 'second' }))
519β
520 const { runWithContext } = getPipeline(formApi, [
521 {
522 run: first,
523 triggers: ['change'],
524 triggerDebounceMs: 100,
525 },
526 {
527 run: second,
528 triggers: ['change'],
529 triggerDebounceMs: 200,
530 },
531 ])
532β
533 const promise = runWithContext({ event: 'change' })
534β
535 await vi.advanceTimersByTimeAsync(100)
536β
537 expect(first).toHaveBeenCalledOnce()
538 expect(second).not.toHaveBeenCalled()
539β
540 await vi.advanceTimersByTimeAsync(100)
541β
542 await expect(promise).resolves.toHaveLength(2)
543β
544 expect(second).toHaveBeenCalledOnce()
545 })
546β
547 it('should not debounce submit validation', async () => {
548 vi.useFakeTimers()
549β
550 const formApi = getForm({ name: '' })
551 const run = vi.fn(() => ({ message: 'foo' }))
552β
553 const { runWithContext } = getPipeline(formApi, [
554 {
555 run,
556 triggers: ['change'],
557 triggerDebounceMs: 100,
558 },
559 ])
560β
561 const results = await runWithContext({ event: 'submit' })
562β
563 expect(run).toHaveBeenCalledOnce()
564 expect(results).toHaveLength(1)
565 })
566β
567 it('should check for enabled triggers', async () => {
568 const formApi = getForm({ name: '' })
569 const run = vi.fn(() => ({ message: 'foo' }))
570β
571 let doThing = false
572β
573 const { runWithContext } = getPipeline(formApi, [
574 {
575 run,
576 triggers: [
577 { trigger: 'change', when: () => doThing },
578 { trigger: 'blur', when: doThing },
579 ],
580 },
581 ])
582β
583 await runWithContext({ event: 'change' })
584 await runWithContext({ event: 'blur' })
585β
586 expect(run).not.toHaveBeenCalled()
587β
588 doThing = true
589β
590 // Since it's a function for enable, it should be the most up to date value
591 await runWithContext({ event: 'change' })
592 expect(run).toHaveBeenCalledOnce()
593 // but blur should have the value stored on its own, not being updated
594 await runWithContext({ event: 'blur' })
595 expect(run).toHaveBeenCalledOnce()
596 })
597β
598 it('should use field value for field-level trigger predicates', async () => {
599 const formApi = getForm({ name: 'test' })
600 const field = formApi._getOrCreateFieldApi({ name: 'name' })
601 const run = vi.fn(() => ({ message: 'foo' }))
602 const when: ValidationPredicateFn<{ name: string }, string> = vi.fn(
603 ({ value }) => value === 'test',
604 )
605β
606 const { runWithContext } = getFieldPipeline(formApi, field, [
607 {
608 run,
609 triggers: [{ trigger: 'change', when }],
610 },
611 ])
612β
613 await runWithContext({ event: 'change' })
614β
615 expect(when).toHaveBeenCalledOnce()
616 expect(when).toHaveBeenCalledWith(
617 expect.objectContaining({
618 scope: 'field',
619 fieldApi: field,
620 value: 'test',
621 }),
622 )
623 expect(run).toHaveBeenCalledOnce()
624 })
625β
626 it('should abort existing debounced validation when same event runs again', async () => {
627 vi.useFakeTimers()
628β
629 const formApi = getForm({ name: '' })
630 const validationResult = { message: 'foo' }
631 const run = vi.fn(() => validationResult)
632 const onResult = vi.fn()
633β
634 const { runWithContext } = getPipeline(formApi, [
635 {
636 run,
637 triggers: ['change'],
638 triggerDebounceMs: 100,
639 },
640 ])
641β
642 const firstPromise = runWithContext({ event: 'change', onResult })
643β
644 await vi.advanceTimersByTimeAsync(50)
645 const secondPromise = runWithContext({ event: 'change', onResult })
646β
647 await vi.advanceTimersByTimeAsync(100)
648β
649 expect(run).toHaveBeenCalledOnce()
650β
651 await firstPromise
652 await secondPromise
653β
654 expect(onResult).toHaveBeenCalledOnce()
655 expect(onResult).toHaveBeenCalledWith(
656 expect.objectContaining({ result: validationResult }),
657 )
658 })
659β
660 it('should abort existing async validation when same event runs again', async () => {
661 const formApi = getForm({ name: '' })
662β
663 let resolveFirstValidation!: () => void
664 const waitForFirstValidation = new Promise<void>((resolve) => {
665 resolveFirstValidation = resolve
666 })
667β
668 const run = vi
669 .fn()
670 .mockResolvedValueOnce(
671 waitForFirstValidation.then(() => ({ message: 'first' })),
672 )
673 .mockResolvedValueOnce({ message: 'second' })
674 const onResult = vi.fn()
675β
676 const { runWithContext } = getPipeline(formApi, [
677 {
678 run,
679 triggers: ['change'],
680 },
681 ])
682β
683 const firstPromise = runWithContext({ event: 'change', onResult })
684 expect(run).toHaveBeenCalledOnce()
685β
686 const secondPromise = runWithContext({ event: 'change', onResult })
687 expect(run).toHaveBeenCalledTimes(2)
688β
689 resolveFirstValidation()
690β
691 await firstPromise
692 await secondPromise
693β
694 expect(onResult).toHaveBeenCalledOnce()
695 expect(onResult).toHaveBeenCalledWith(
696 expect.objectContaining({ result: { message: 'second' } }),
697 )
698 })
699β
700 it('should not call onResult for aborted debounced calls', async () => {
701 vi.useFakeTimers()
702β
703 const formApi = getForm({ name: '' })
704 const validationResult = { message: 'foo' }
705 const run = vi.fn(() => validationResult)
706 const onResult = vi.fn()
707β
708 const { runWithContext, pipeline } = getPipeline(formApi, [
709 {
710 run,
711 triggers: ['change'],
712 triggerDebounceMs: 100,
713 },
714 ])
715β
716 const firstPromise = runWithContext({ event: 'change', onResult })
717β
718 await vi.advanceTimersByTimeAsync(50)
719 const secondPromise = runWithContext({ event: 'change', onResult })
720β
721 await vi.advanceTimersByTimeAsync(100)
722β
723 expect(run).toHaveBeenCalledOnce()
724β
725 await firstPromise
726 await secondPromise
727β
728 expect(onResult).toHaveBeenCalledOnce()
729 expect(onResult).toHaveBeenCalledWith(
730 expect.objectContaining({
731 validatorInstance: pipeline[0],
732 result: validationResult,
733 }),
734 )
735 })
736β
737 it('should use the correct fieldApi when debounced validation is triggered by different fields', async () => {
738 vi.useFakeTimers()
739β
740 const formApi = getForm({ users: ['a', 'b', 'c'] })
741 const receivedFieldApiNames: Array<string> = []
742β
743 const { runWithContext } = getPipeline(formApi, [
744 {
745 run: ({ triggerFieldApi }) => {
746 if (triggerFieldApi) {
747 receivedFieldApiNames.push(triggerFieldApi.name)
748 }
749 return null
750 },
751 triggers: ['change'],
752 triggerDebounceMs: 100,
753 },
754 ])
755β
756 // Get or create field APIs for users[1] and users[2]
757 const field1 = formApi._getOrCreateFieldApi({ name: 'users[1]' })
758 const field2 = formApi._getOrCreateFieldApi({ name: 'users[2]' })
759β
760 // Trigger validation for users[1]
761 const firstPromise = runWithContext({ event: 'change', field: field1 })
762β
763 // Advance time partially (before debounce completes)
764 await vi.advanceTimersByTimeAsync(50)
765β
766 // Trigger validation for users[2] (this should abort the first debounced call)
767 const secondPromise = runWithContext({ event: 'change', field: field2 })
768β
769 // Advance time to complete the debounce
770 await vi.advanceTimersByTimeAsync(100)
771β
772 await firstPromise
773 await secondPromise
774β
775 // The validator should have been called once with users[2], not users[1]
776 expect(receivedFieldApiNames).toHaveLength(1)
777 expect(receivedFieldApiNames[0]).toBe('users[2]')
778 })
779β
780 describe('Standard Schema validation', () => {
781 it('should infer standard schema validator output types', () => {
782 const lengthSchema = z
783 .object({
784 name: z.string(),
785 })
786 .transform(({ name }) => ({ nameLength: name.length }))
787 const uppercaseSchema = z
788 .object({
789 name: z.string(),
790 })
791 .transform(({ name }) => ({ upperName: name.toUpperCase() }))
792β
793 type Output = ToFormOutputs<
794 [
795 { run: typeof lengthSchema; triggers: [] },
796 { run: typeof uppercaseSchema; triggers: [] },
797 ]
798 >
799β
800 expectTypeOf<Output>().toEqualTypeOf<
801 [
802 {
803 nameLength: number
804 },
805 {
806 upperName: string
807 },
808 ]
809 >()
810 })
811β
812 it('should infer onSubmit value from standard schema validators', () => {
813 const schema = z
814 .object({
815 name: z.string(),
816 })
817 .transform(({ name }) => ({ nameLength: name.length }))
818β
819 new InternalFormApi({
820 defaultValues: { name: '' },
821 validators: [{ run: schema, triggers: [] }],
822 onSubmit: ({ value, validatorOutputs }) => {
823 expectTypeOf(value).toEqualTypeOf<{ name: string }>()
824 expectTypeOf(validatorOutputs).toEqualTypeOf<
825 readonly [{ nameLength: number }]
826 >()
827 },
828 })
829β
830 const schema2 = z
831 .object({
832 name: z.string(),
833 })
834 .transform(({ name }) => ({ date: new Date(name.length) }))
835β
836 new InternalFormApi({
837 defaultValues: { name: '' },
838 validators: [
839 { run: schema, triggers: [] },
840 { run: () => false, triggers: [] },
841 { run: schema2, triggers: [] },
842 ],
843 onSubmit: ({ value, validatorOutputs }) => {
844 expectTypeOf(value).toEqualTypeOf<{ name: string }>()
845 expectTypeOf(validatorOutputs).toEqualTypeOf<
846 readonly [{ nameLength: number }, undefined, { date: Date }]
847 >()
848 },
849 })
850 })
851β
852 it('should pass standard schema output to onSubmit', async () => {
853 const onSubmit = vi.fn()
854 const schema = z
855 .object({
856 name: z.string(),
857 })
858 .transform(({ name }) => ({ nameLength: name.length }))
859 const form = new InternalFormApi({
860 defaultValues: { name: 'test' },
861 validators: [{ run: schema, triggers: [] }],
862 onSubmit,
863 })
864β
865 await form.handleSubmit()
866β
867 expect(onSubmit).toHaveBeenCalledWith(
868 expect.objectContaining({
869 value: { name: 'test' },
870 validatorOutputs: [{ nameLength: 4 }],
871 }),
872 )
873 })
874β
875 /**
876 * Assert that the result consists of certain fields with certain errors.
877 *
878 * {
879 * // ...any
880 * result: {
881 * // ...any
882 * fields: {
883 * fieldName: []
884 * }
885 * }
886 * }
887 */
888 function getFieldErrorMatcher(fields: Record<string, Array<string>>) {
889 const fieldMatchers = Object.fromEntries(
890 Object.entries(fields).map(([fieldName, messages]) => [
891 fieldName,
892 expect.arrayContaining(
893 messages.map((message) =>
894 expect.objectContaining({
895 message,
896 }),
897 ),
898 ),
899 ]),
900 )
901β
902 return expect.objectContaining({
903 result: expect.objectContaining({
904 fields: fieldMatchers,
905 }),
906 })
907 }
908β
909 it('should validate form with a successful zod schema', async () => {
910 const formApi = getForm({ name: 'test', age: 25 })
911β
912 const schema = z.object({
913 name: z.string().min(1),
914 age: z.number().min(0),
915 })
916β
917 const { runWithContext, pipeline } = getPipeline(formApi, [
918 {
919 run: schema,
920 triggers: [],
921 },
922 ])
923β
924 const results = await runWithContext({ event: 'submit' })
925β
926 expect(results).toHaveLength(1)
927 expect(results[0]?.result).toBeNull()
928 expect(results[0]?.output).toEqual({
929 name: 'test',
930 age: 25,
931 })
932 expect(pipeline[0]?.hasOutput).toBe(true)
933 expect(pipeline[0]?.output).toEqual({
934 name: 'test',
935 age: 25,
936 })
937 })
938β
939 it.each(['change', 'blur'] as const)(
940 'does not store schema output during %s validation',
941 async (event) => {
942 const formApi = getForm({ name: 'test' })
943 const schema = z.object({ name: z.string() })
944 const { runWithContext, pipeline } = getPipeline(formApi, [
945 {
946 run: schema,
947 triggers: [event],
948 },
949 ])
950β
951 const results = await runWithContext({ event })
952β
953 expect(results[0]?.output).toEqual({ name: 'test' })
954 expect(pipeline[0]?.hasOutput).toBe(false)
955 },
956 )
957β
958 it('does not store field schema output during submit validation', async () => {
959 const formApi = getForm({ name: 'test' })
960 const field = formApi._getOrCreateFieldApi({ name: 'name' })
961 const schema = z.string().transform((name) => name.toUpperCase())
962 const { runWithContext, pipeline } = getFieldPipeline(formApi, field, [
963 {
964 run: schema,
965 triggers: [],
966 },
967 ])
968β
969 const results = await runWithContext({ event: 'submit' })
970β
971 expect(results[0]?.output).toBe('TEST')
972 expect(pipeline[0]?.hasOutput).toBe(false)
973 })
974β
975 it('commits schema output before notifying onResult', async () => {
976 const formApi = getForm({ name: 'test' })
977 const schema = z.object({ name: z.string() })
978 const { runWithContext, pipeline } = getPipeline(formApi, [
979 {
980 run: schema,
981 triggers: [],
982 },
983 ])
984 const onResult = vi.fn(() => {
985 expect(pipeline[0]?.hasOutput).toBe(true)
986 expect(pipeline[0]?.output).toEqual({ name: 'test' })
987 })
988β
989 await runWithContext({ event: 'submit', onResult })
990β
991 expect(onResult).toHaveBeenCalledOnce()
992 })
993β
994 it('does not commit stale async schema output', async () => {
995 const formApi = getForm({ name: 'stale' })
996 let resolveFirst!: (result: { value: { name: string } }) => void
997 const firstResult = new Promise<{ value: { name: string } }>(
998 (resolve) => {
999 resolveFirst = resolve
1000 },
1001 )
1002 const schema = {
1003 '~standard': {
1004 version: 1,
1005 vendor: 'test',
1006 validate: vi
1007 .fn()
1008 .mockReturnValueOnce(firstResult)
1009 .mockReturnValueOnce({ value: { name: 'current' } }),
1010 },
1011 } satisfies StandardSchemaV1<{ name: string }, { name: string }>
1012 const { runWithContext, pipeline } = getPipeline(formApi, [
1013 {
1014 run: schema,
1015 triggers: [],
1016 },
1017 ])
1018β
1019 const staleValidation = runWithContext({ event: 'submit' })
1020 formApi.setFieldValue('name', 'current')
1021 const currentValidation = runWithContext({ event: 'submit' })
1022β
1023 await Promise.all([staleValidation, currentValidation])
1024 expect(pipeline[0]?.output).toEqual({ name: 'current' })
1025β
1026 resolveFirst({ value: { name: 'stale' } })
1027 await new Promise((resolve) => setTimeout(resolve, 0))
1028β
1029 expect(pipeline[0]?.output).toEqual({ name: 'current' })
1030 })
1031β
1032 it('clears schema output before a validator is skipped by bailIfInvalid', async () => {
1033 const formApi = getForm({ name: 'test' })
1034 let shouldFail = false
1035 const { runWithContext, pipeline } = getPipeline(formApi, [
1036 {
1037 run: () => (shouldFail ? 'Invalid' : null),
1038 triggers: [],
1039 },
1040 {
1041 bailIfInvalid: true,
1042 run: z.object({ name: z.string() }),
1043 triggers: [],
1044 },
1045 ])
1046β
1047 await runWithContext({ event: 'submit' })
1048 expect(pipeline[1]?.hasOutput).toBe(true)
1049β
1050 shouldFail = true
1051 await runWithContext({ event: 'submit' })
1052β
1053 expect(pipeline[1]?.hasOutput).toBe(false)
1054 expect(pipeline[1]?.output).toBeUndefined()
1055 })
1056β
1057 it('aborts pending schema output before a dynamic predicate skips the validator', async () => {
1058 const formApi = getForm({ name: 'stale' })
1059 let shouldSkipOnSubmit = false
1060 let resolveSchema!: (result: { value: { name: string } }) => void
1061 const output = new Promise<{ value: { name: string } }>((resolve) => {
1062 resolveSchema = resolve
1063 })
1064 const schema = {
1065 '~standard': {
1066 version: 1,
1067 vendor: 'test',
1068 validate: () => output,
1069 },
1070 } satisfies StandardSchemaV1<{ name: string }, { name: string }>
1071 const { runWithContext, pipeline } = getPipeline(formApi, [
1072 {
1073 run: schema,
1074 skipOnSubmit: () => shouldSkipOnSubmit,
1075 triggers: [],
1076 },
1077 ])
1078β
1079 const staleValidation = runWithContext({ event: 'submit' })
1080 shouldSkipOnSubmit = true
1081 await runWithContext({ event: 'submit' })
1082 await staleValidation
1083β
1084 resolveSchema({ value: { name: 'stale' } })
1085 await new Promise((resolve) => setTimeout(resolve, 0))
1086β
1087 expect(pipeline[0]?.hasOutput).toBe(false)
1088 expect(pipeline[0]?.output).toBeUndefined()
1089 })
1090β
1091 it('should validate form with a failing zod schema', async () => {
1092 const formApi = getForm({ name: '', age: 25 })
1093β
1094 const schema = z.object({
1095 name: z.string().min(1, 'Name is required'),
1096 age: z.number().min(0),
1097 })
1098β
1099 const { runWithContext } = getPipeline(formApi, [
1100 {
1101 run: schema,
1102 triggers: [],
1103 },
1104 ])
1105β
1106 const results = await runWithContext({ event: 'submit' })
1107β
1108 expect(results).toEqual([
1109 getFieldErrorMatcher({ name: ['Name is required'] }),
1110 ])
1111 expect(results[0]?.output).toBeNull()
1112 })
1113β
1114 it('should validate form with multiple errors from zod schema', async () => {
1115 const formApi = getForm({ name: '', age: -5 })
1116β
1117 const schema = z.object({
1118 name: z.string().min(1, 'Name is required'),
1119 age: z.number().min(0, 'Age must be positive'),
1120 })
1121β
1122 const { runWithContext } = getPipeline(formApi, [
1123 {
1124 run: schema,
1125 triggers: [],
1126 },
1127 ])
1128β
1129 const results = await runWithContext({ event: 'submit' })
1130β
1131 expect(results).toEqual([
1132 getFieldErrorMatcher({
1133 name: ['Name is required'],
1134 age: ['Age must be positive'],
1135 }),
1136 ])
1137 })
1138β
1139 it('should validate form with nested path errors from zod schema', async () => {
1140 const formApi = getForm({ user: { name: '', email: '' } })
1141β
1142 const schema = z.object({
1143 user: z.object({
1144 name: z.string().min(1, 'Name is required'),
1145 email: z.email('Email is invalid'),
1146 }),
1147 })
1148β
1149 const { runWithContext } = getPipeline(formApi, [
1150 {
1151 run: schema,
1152 triggers: [],
1153 },
1154 ])
1155β
1156 const results = await runWithContext({ event: 'submit' })
1157β
1158 expect(results).toHaveLength(1)
1159 expect(results).toEqual([
1160 getFieldErrorMatcher({
1161 'user.name': ['Name is required'],
1162 'user.email': ['Email is invalid'],
1163 }),
1164 ])
1165 })
1166β
1167 it('should validate form with array path errors from zod schema', async () => {
1168 const formApi = getForm({ users: [{ name: '' }, { name: '' }] })
1169β
1170 const schema = z.object({
1171 users: z.array(
1172 z.object({
1173 name: z.string().min(1, 'Name is required'),
1174 }),
1175 ),
1176 })
1177β
1178 const { runWithContext } = getPipeline(formApi, [
1179 {
1180 run: schema,
1181 triggers: [],
1182 },
1183 ])
1184β
1185 const results = await runWithContext({ event: 'submit' })
1186β
1187 expect(results).toEqual([
1188 getFieldErrorMatcher({
1189 'users[0].name': ['Name is required'],
1190 'users[1].name': ['Name is required'],
1191 }),
1192 ])
1193 })
1194β
1195 it('should run zod schema validators with matching signal', async () => {
1196 const formApi = getForm({ name: '' })
1197β
1198 const schema = z.object({
1199 name: z.string().min(1, 'Name is required'),
1200 })
1201β
1202 const { runWithContext } = getPipeline(formApi, [
1203 {
1204 run: schema,
1205 triggers: ['change'],
1206 },
1207 ])
1208β
1209 const blurResults = await runWithContext({ event: 'blur' })
1210 expect(blurResults).toHaveLength(0)
1211β
1212 const changeResults = await runWithContext({ event: 'change' })
1213 expect(changeResults).toEqual([
1214 getFieldErrorMatcher({ name: ['Name is required'] }),
1215 ])
1216β
1217 const submitResults = await runWithContext({ event: 'change' })
1218 expect(submitResults).toEqual([
1219 getFieldErrorMatcher({ name: ['Name is required'] }),
1220 ])
1221 })
1222β
1223 it('should respect bailIfInvalid with zod schema validators', async () => {
1224 const formApi = getForm({ name: '' })
1225β
1226 const failingSchema = z.object({
1227 name: z.string().min(1, 'Name is required'),
1228 })
1229β
1230 const passingSchema = z.object({
1231 name: z.string(),
1232 })
1233β
1234 const validateSpy = vi.fn(() => null)
1235β
1236 const { runWithContext } = getPipeline(formApi, [
1237 {
1238 run: failingSchema,
1239 triggers: [],
1240 },
1241 {
1242 run: passingSchema,
1243 triggers: [],
1244 bailIfInvalid: true,
1245 },
1246 {
1247 run: validateSpy,
1248 triggers: [],
1249 bailIfInvalid: true,
1250 },
1251 ])
1252β
1253 const results = await runWithContext({ event: 'submit' })
1254β
1255 expect(results[0]).toEqual(
1256 getFieldErrorMatcher({ name: ['Name is required'] }),
1257 )
1258 expect(validateSpy).not.toHaveBeenCalled()
1259 })
1260β
1261 it('should work with async zod schema validation', async () => {
1262 const formApi = getForm({ name: '' })
1263β
1264 // Zod schemas can be async with refinements
1265 const schema = z.object({
1266 name: z
1267 .string()
1268 .refine(async (val) => val.length > 0, 'Name is required'),
1269 })
1270β
1271 const { runWithContext } = getPipeline(formApi, [
1272 {
1273 run: schema,
1274 triggers: [],
1275 },
1276 ])
1277β
1278 const results = await runWithContext({ event: 'submit' })
1279β
1280 expect(results).toEqual([
1281 getFieldErrorMatcher({ name: ['Name is required'] }),
1282 ])
1283 })
1284β
1285 it('should not run zod schema validators with skipOnSubmit enabled', async () => {
1286 const formApi = getForm({ name: '' })
1287β
1288 const schema = z.object({
1289 name: z.string().min(1, 'Name is required'),
1290 })
1291β
1292 const { runWithContext } = getPipeline(formApi, [
1293 {
1294 run: schema,
1295 triggers: [],
1296 skipOnSubmit: true,
1297 },
1298 ])
1299β
1300 const submitResults = await runWithContext({ event: 'submit' })
1301 expect(submitResults).toHaveLength(0)
1302β
1303 const changeResults = await runWithContext({ event: 'change' })
1304 expect(changeResults).toHaveLength(0)
1305 })
1306 })
1307β
1308 describe('validator errors', () => {
1309 it('should handle validator thrown errors gracefully without bubbling', async () => {
1310 vi.useFakeTimers()
1311 const formApi = getForm({ name: '' })
1312 const consoleErrorSpy = vi
1313 .spyOn(console, 'error')
1314 .mockImplementation(() => {})
1315β
1316 const { runWithContext } = getPipeline(formApi, [
1317 {
1318 run: () => {
1319 // Valid validation result
1320 return { message: 'first validator' }
1321 },
1322 triggers: [],
1323 },
1324 {
1325 run: () => {
1326 // This will throw: Cannot read property 'foo' of undefined
1327 const obj: any = undefined
1328 return obj.foo.bar
1329 },
1330 triggers: [],
1331 },
1332 ])
1333β
1334 // Should not throw - promise should resolve
1335 const promise = runWithContext({
1336 event: 'submit',
1337 hasFailedBefore: false,
1338 })
1339 await vi.runAllTimersAsync()
1340β
1341 await expect(promise).resolves.toBeDefined()
1342 // Should have logged the error
1343 expect(consoleErrorSpy).toHaveBeenCalled()
1344β
1345 consoleErrorSpy.mockRestore()
1346 })
1347β
1348 it('should handle async validator thrown errors', async () => {
1349 vi.useFakeTimers()
1350 const formApi = getForm({ name: '' })
1351 const consoleErrorSpy = vi
1352 .spyOn(console, 'error')
1353 .mockImplementation(() => {})
1354β
1355 const { runWithContext } = getPipeline(formApi, [
1356 {
1357 run: async () => {
1358 return Promise.resolve({ message: 'first validator' })
1359 },
1360 triggers: [],
1361 },
1362 {
1363 run: async () => {
1364 await Promise.reject()
1365 return null
1366 },
1367 triggers: [],
1368 },
1369 ])
1370β
1371 // Should not throw - promise should resolve
1372 const promise = runWithContext({
1373 event: 'submit',
1374 hasFailedBefore: false,
1375 })
1376β
1377 await vi.runAllTimersAsync()
1378 await expect(promise).resolves.toBeDefined()
1379 expect(consoleErrorSpy).toHaveBeenCalled()
1380β
1381 consoleErrorSpy.mockRestore()
1382 })
1383β
1384 it('should handle errors in debounced validators', async () => {
1385 vi.useFakeTimers()
1386 const formApi = getForm({ name: '' })
1387 const consoleErrorSpy = vi
1388 .spyOn(console, 'error')
1389 .mockImplementation(() => {})
1390β
1391 const { runWithContext } = getPipeline(formApi, [
1392 {
1393 run: () => {
1394 throw new Error('Debounced error')
1395 },
1396 triggers: ['change'],
1397 triggerDebounceMs: 100,
1398 },
1399 ])
1400β
1401 const promise = runWithContext({ event: 'change' })
1402β
1403 await vi.advanceTimersByTimeAsync(100)
1404β
1405 await expect(promise).resolves.toBeDefined()
1406 expect(consoleErrorSpy).toHaveBeenCalled()
1407β
1408 consoleErrorSpy.mockRestore()
1409 })
1410 })
1411β
1412 describe('edge cases', () => {
1413 it('should return empty results for killed fields', async () => {
1414 const formApi = getForm({ name: 'test' })
1415 const field = formApi._getOrCreateFieldApi({ name: 'name' })
1416β
1417 // Mark the field as killed
1418 field._isKilled = true
1419β
1420 const pipeline: Array<FieldValidator<{ name: string }, 'name', string>> =
1421 [
1422 {
1423 run: vi.fn(() => ({ message: 'should not be called' })),
1424 triggers: ['change'],
1425 },
1426 ]
1427β
1428 const { runWithContext } = getFieldPipeline(formApi, field, pipeline)
1429β
1430 const results = await runWithContext({ event: 'change' })
1431β
1432 expect(results).toHaveLength(0)
1433 })
1434 })
1435})