From 55d69a2698955bdb481509fb71fdd57cf2aa60fb Mon Sep 17 00:00:00 2001 From: 0froq Date: Sat, 21 Nov 2026 09:37:23 +0800 Subject: [PATCH 1/6] feat: accept nested validation error paths in useForm errors Validators report nested messages as dotted keys such as `profile.name` or `contacts.0.email`. The error map, `setError()` and `clearErrors()` now take those keys, so apps no longer need a cast to read or clear them. --- .../react/test/unit/use-form.typecheck.ts | 21 +++++++++++++++++++ .../solid/test/unit/form-errors.typecheck.ts | 21 +++++++++++++++++++ .../svelte/test/unit/form-errors.typecheck.ts | 21 +++++++++++++++++++ packages/void/src/pages/client.ts | 2 ++ packages/void/src/pages/form-presentation.ts | 21 ++++++++++++++++--- .../vue/test/unit/form-errors.typecheck.ts | 21 +++++++++++++++++++ 6 files changed, 104 insertions(+), 3 deletions(-) diff --git a/packages/react/test/unit/use-form.typecheck.ts b/packages/react/test/unit/use-form.typecheck.ts index cad0ce449..08b274d9b 100644 --- a/packages/react/test/unit/use-form.typecheck.ts +++ b/packages/react/test/unit/use-form.typecheck.ts @@ -5,9 +5,30 @@ declare module 'void/routes' { interface PageActionMap { '/__form-options/notes': { actions: { create: { body: { title: string } } } }; '/__form-options/notes/:id': { body: { title: string }; params: { id: string } }; + '/__form-options/nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('/__form-options/nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFormOptions(): void { useForm( '/__form-options/notes?create', diff --git a/packages/solid/test/unit/form-errors.typecheck.ts b/packages/solid/test/unit/form-errors.typecheck.ts index 5849df88e..b302da404 100644 --- a/packages/solid/test/unit/form-errors.typecheck.ts +++ b/packages/solid/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.ts'; declare module 'void/routes' { interface PageActionMap { '/__form-errors/solid': { body: { email: string } }; + '/__form-errors/solid-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('/__form-errors/solid-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.setData('contacts', [{ email: 'alex@example.com' }]); + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('/__form-errors/solid', { email: '' }); form.setError('email', 'Invalid email'); diff --git a/packages/svelte/test/unit/form-errors.typecheck.ts b/packages/svelte/test/unit/form-errors.typecheck.ts index 024ba82b0..be7220ce2 100644 --- a/packages/svelte/test/unit/form-errors.typecheck.ts +++ b/packages/svelte/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.svelte.ts'; declare module 'void/routes' { interface PageActionMap { '/__form-errors/svelte': { body: { email: string } }; + '/__form-errors/svelte-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('/__form-errors/svelte-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.errors['contacts.0.email'] = 'Required email'; + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('/__form-errors/svelte', { email: '' }); form.setError('email', 'Invalid email'); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index f2039b7a3..a14a84d81 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -649,6 +649,8 @@ export { formRetryMessage, formSubmissionBlocked, scheduleFormRetry, + type FormErrorPath, + type FormErrors, type FormModel, type FormMethod, type FormState, diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index f5d0772da..81e1356f2 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -20,8 +20,23 @@ export type FormStatus = { readonly wasSuccessful: boolean; readonly recentlySuccessful: boolean; }; +/** + * A body field plus the dotted nested paths a validator reports for it, such as `profile.name` + * or `contacts.0.email`. The recursion is capped so a recursive body type stays cheap to check. + */ +export type FormErrorPath = []> = Depth['length'] extends 6 + ? never + : T extends ReadonlyArray + ? `${number}` | `${number}.${FormErrorPath}` + : T extends object + ? { + [K in keyof T & string]: T[K] extends (...args: Array) => unknown + ? never + : K | `${K}.${FormErrorPath}`; + }[keyof T & string] + : never; /** Field-keyed validation messages; a field without an error is absent. */ -export type FormErrors = Partial>; +export type FormErrors = Partial, string>>; /** * How an adapter's apps change `data` and `errors`, following its framework's idiom. * `'in-place'`: apps edit them directly (Vue, Svelte). @@ -40,8 +55,8 @@ export type FormState = FormStatus & Readonly<{ reset(options: FormResetOptions, ...fields: ReadonlyArray): void; reset(...fields: ReadonlyArray): void; - setError(field: keyof TData & string, message: string): void; - clearErrors(...fields: ReadonlyArray): void; + setError(field: FormErrorPath, message: string): void; + clearErrors(...fields: ReadonlyArray>): void; clearError(): void; }>; /** diff --git a/packages/vue/test/unit/form-errors.typecheck.ts b/packages/vue/test/unit/form-errors.typecheck.ts index ab336a67f..35c64b660 100644 --- a/packages/vue/test/unit/form-errors.typecheck.ts +++ b/packages/vue/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.ts'; declare module 'void/routes' { interface PageActionMap { '/__form-errors/vue': { body: { email: string } }; + '/__form-errors/vue-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('/__form-errors/vue-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.errors['contacts.0.email'] = 'Required email'; + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('/__form-errors/vue', { email: '' }); form.setError('email', 'Invalid email'); From 2817e8dd50f5a3fa0118a149f824fc03b7da4c00 Mon Sep 17 00:00:00 2001 From: 0froq Date: Sat, 21 Nov 2026 09:37:51 +0800 Subject: [PATCH 2/6] fix: clear nested form errors with their parent field Editing or replacing a parent object or array now clears the errors of the fields below it, matching how editing a scalar clears that field's error. Clearing a parent with `clearErrors()` does the same and keeps unrelated errors. Svelte snapshots the parent field when a handler reports a nested error, because the parent is what changed in `data`. --- packages/react/src/runtime/use-form.ts | 11 ++-- packages/react/test/unit/use-form.test.ts | 59 +++++++++++++++++++ packages/solid/src/runtime/use-form.ts | 11 +--- packages/solid/test/unit/form-errors.test.ts | 45 ++++++++++++-- .../svelte/src/runtime/use-form.svelte.ts | 17 +++++- packages/svelte/test/unit/use-form.test.ts | 27 +++++++++ packages/void/src/pages/client.ts | 2 + packages/void/src/pages/form-presentation.ts | 17 ++++++ packages/vue/src/runtime/use-form.ts | 13 +++- packages/vue/test/unit/use-form.test.ts | 32 ++++++++++ 10 files changed, 207 insertions(+), 27 deletions(-) diff --git a/packages/react/src/runtime/use-form.ts b/packages/react/src/runtime/use-form.ts index fdf55b190..f9f3ad80a 100644 --- a/packages/react/src/runtime/use-form.ts +++ b/packages/react/src/runtime/use-form.ts @@ -15,6 +15,7 @@ import { isAbortError, isCallSiteActionError, isEqualFormValue, + omitFormErrors, parseFormResetArgs, submitAction, type FormResetOptions, @@ -200,11 +201,10 @@ export function useForm( const target = callbackOutcomeRef.current ?? outcome; setErrorEdits((prev) => { const current = resolveOutcomeErrors(target, prev); - if (!(field in current)) { + const next = omitFormErrors(current, [field]); + if (next === current) { return prev; } - const next = { ...current }; - delete next[field]; return { ...(prev?.source === target ? prev : { source: target }), errors: next, @@ -241,10 +241,7 @@ export function useForm( if (fields.length === 0) { return { ...base, errors: EMPTY_ERRORS }; } - const next = { ...resolveOutcomeErrors(target, prev) }; - for (const field of fields) { - delete next[field]; - } + const next = omitFormErrors(resolveOutcomeErrors(target, prev), fields); return { ...base, errors: next }; }); }, diff --git a/packages/react/test/unit/use-form.test.ts b/packages/react/test/unit/use-form.test.ts index 8bca58a20..d95561a12 100644 --- a/packages/react/test/unit/use-form.test.ts +++ b/packages/react/test/unit/use-form.test.ts @@ -22,6 +22,9 @@ import { useIslandForm, type IslandFormReturn } from '../../src/runtime/use-isla declare module 'void/routes' { interface PageActionMap { '/__form-callbacks/notes': { actions: { create: { body: { title: string } } } }; + '/__form-nested/contacts': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } @@ -247,6 +250,62 @@ describe('useForm callbacks', () => { expect(formRef.current!.error).toBe(actionError); }); + it('clears nested errors below a replaced parent field and a cleared parent', async () => { + type NestedForm = ReturnType>; + const formRef: { current: NestedForm | null } = { current: null }; + function App() { + formRef.current = useForm('/__form-nested/contacts', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + return null; + } + const router = routerWithVisit( + vi.fn(async () => ({ + errors: { + 'profile.name': 'Required name', + 'contacts.0.email': 'Required email', + title: 'Unrelated', + }, + })), + ); + await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App))); + const form = () => formRef.current!; + const submit = () => + act(async () => { + startTransition(() => { + form().post(new FormData()); + }); + }); + + await submit(); + expect(form().errors['profile.name']).toBe('Required name'); + expect(form().errors['contacts.0.email']).toBe('Required email'); + + await act(async () => { + form().setData('profile', { name: 'Alex' }); + }); + expect(form().errors['profile.name']).toBeUndefined(); + expect(form().errors['contacts.0.email']).toBe('Required email'); + + await act(async () => { + form().setData('contacts', [{ email: 'alex@example.com' }]); + }); + expect(form().errors).toEqual({ title: 'Unrelated' }); + + await submit(); + await act(async () => { + form().clearErrors('profile'); + }); + expect(form().errors['profile.name']).toBeUndefined(); + expect(form().errors['contacts.0.email']).toBe('Required email'); + + await act(async () => { + form().clearErrors('contacts'); + }); + expect(form().errors).toEqual({ title: 'Unrelated' }); + }); + it('fires onSuccess on each successful submit', async () => { const onSuccess = vi.fn(); const { formRef } = await mountForm( diff --git a/packages/solid/src/runtime/use-form.ts b/packages/solid/src/runtime/use-form.ts index 3f8cb3aff..7aa900c2b 100644 --- a/packages/solid/src/runtime/use-form.ts +++ b/packages/solid/src/runtime/use-form.ts @@ -8,6 +8,7 @@ import { isAbortError, isCallSiteActionError, isEqualFormValue, + omitFormErrors, parseFormResetArgs, submitAction, type FormResetOptions, @@ -105,15 +106,7 @@ export function useForm( } function clearErrors(...fields: ReadonlyArray) { - if (fields.length === 0) { - replaceErrors({}); - } else { - const next = { ...errors() }; - for (const field of fields) { - delete next[field]; - } - replaceErrors(next); - } + replaceErrors(fields.length === 0 ? {} : omitFormErrors(errors(), fields)); } function setFieldError(field: string, message: string) { diff --git a/packages/solid/test/unit/form-errors.test.ts b/packages/solid/test/unit/form-errors.test.ts index e6098acd4..954353029 100644 --- a/packages/solid/test/unit/form-errors.test.ts +++ b/packages/solid/test/unit/form-errors.test.ts @@ -20,17 +20,17 @@ const useForm = typedUseForm as unknown as ( defaults: Record, ) => TestForm; -function createForm() { - const [serverErrors, setServerErrors] = createSignal({ - email: 'Invalid email', - name: 'Required', - }); +function createForm( + server: Record = { email: 'Invalid email', name: 'Required' }, + defaults: Record = { email: '', name: '' }, +) { + const [serverErrors, setServerErrors] = createSignal(server); let form!: TestForm; const dispose = createRoot((dispose) => { createComponent(ErrorsContext.Provider, { value: serverErrors, get children() { - form = useForm('/test', { email: '', name: '' }); + form = useForm('/test', defaults); return null; }, }); @@ -66,6 +66,39 @@ describe('useForm router errors', () => { } }); + it('clears nested errors below a replaced parent field and a cleared parent', () => { + const { form, dispose } = createForm( + { + 'profile.name': 'Required name', + 'contacts.0.email': 'Required email', + name: 'Unrelated', + }, + { profile: { name: '' }, contacts: [{ email: '' }] }, + ); + try { + expect(form.errors).toEqual({ + 'profile.name': 'Required name', + 'contacts.0.email': 'Required email', + name: 'Unrelated', + }); + + form.clearErrors('profile'); + expect(form.errors).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + + form.setError('profile.name', 'Required name'); + form.setData('profile', { name: 'Alex' }); + expect(form.errors).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + + form.setData('contacts', [{ email: 'alex@example.com' }]); + expect(form.errors).toEqual({ name: 'Unrelated' }); + + form.clearErrors('name'); + expect(form.errors).toEqual({}); + } finally { + dispose(); + } + }); + it('shows new server results after earlier errors were cleared', () => { const { form, setServerErrors, dispose } = createForm(); try { diff --git a/packages/svelte/src/runtime/use-form.svelte.ts b/packages/svelte/src/runtime/use-form.svelte.ts index f01e7533d..6a76aeb9a 100644 --- a/packages/svelte/src/runtime/use-form.svelte.ts +++ b/packages/svelte/src/runtime/use-form.svelte.ts @@ -7,6 +7,7 @@ import { isAbortError, isCallSiteActionError, isEqualFormValue, + isFormErrorWithin, parseFormResetArgs, submitAction, type FormResetOptions, @@ -57,7 +58,11 @@ export function useForm( untrack(() => { for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(current)])) { if (!isEqualFormValue(current[key], dataSnapshot[key])) { - delete errors[key]; + for (const errorKey of Object.keys(errors)) { + if (isFormErrorWithin(errorKey, key)) { + delete errors[errorKey]; + } + } } } dataSnapshot = current; @@ -65,9 +70,11 @@ export function useForm( }); // An input handler may validate its new value before the change effect runs. + // Nested error keys snapshot the parent field, which owns the changed value. function snapshotField(field: string) { + const [parent] = field.split('.'); untrack(() => { - dataSnapshot = { ...dataSnapshot, [field]: cloneFormValue(data[field]) }; + dataSnapshot = { ...dataSnapshot, [parent]: cloneFormValue(data[parent]) }; }); } @@ -106,7 +113,11 @@ export function useForm( errors = {}; } else { for (const field of fields) { - delete errors[field]; + for (const key of Object.keys(errors)) { + if (isFormErrorWithin(key, field)) { + delete errors[key]; + } + } } } } diff --git a/packages/svelte/test/unit/use-form.test.ts b/packages/svelte/test/unit/use-form.test.ts index 714c6d1be..1fa0593b7 100644 --- a/packages/svelte/test/unit/use-form.test.ts +++ b/packages/svelte/test/unit/use-form.test.ts @@ -18,6 +18,7 @@ type TestForm = { readonly pending: boolean; readonly wasSuccessful: boolean; setError(field: string, message: string): void; + clearErrors(...fields: Array): void; reset(): void; post(): Promise; }; @@ -154,6 +155,32 @@ describe('useForm field errors', () => { expect({ ...form.errors }).toEqual({ name: 'Name invalid' }); }); + it('clears nested errors below an edited parent field and a cleared parent', () => { + const form = mountForm({ profile: { name: '' }, contacts: [{ email: '' }] }); + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.setError('name', 'Unrelated'); + svelte.flushSync(); + + form.data.profile = { name: 'Alex' }; + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + + form.data.contacts = [{ email: 'alex@example.com' }]; + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ name: 'Unrelated' }); + + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.clearErrors('profile'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + + form.clearErrors('contacts'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ name: 'Unrelated' }); + }); + it('clears an error written before the field edit in the same handler', () => { const form = mountForm({ email: '' }); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index a14a84d81..47a7d72b2 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -648,6 +648,8 @@ export { formErrorMessage, formRetryMessage, formSubmissionBlocked, + isFormErrorWithin, + omitFormErrors, scheduleFormRetry, type FormErrorPath, type FormErrors, diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index 81e1356f2..75348957d 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -76,6 +76,23 @@ export type IslandFormState = FormStatus & delete(url: RouteUrl): Promise; }>; +/** Whether an error key names `field` or a nested field below it, such as `profile.name`. */ +export function isFormErrorWithin(key: string, field: string): boolean { + return key === field || key.startsWith(`${field}.`); +} +/** + * Removes the errors of `fields` and of the nested fields below them, keeping unrelated errors. + * Returns the same object when no error matched, so callers can skip an update. + */ +export function omitFormErrors( + errors: Record, + fields: ReadonlyArray, +): Record { + const kept = Object.entries(errors).filter( + ([key]) => !fields.some((field) => isFormErrorWithin(key, field)), + ); + return kept.length === Object.keys(errors).length ? errors : Object.fromEntries(kept); +} export function formErrorMessage(form: Pick): string | null { return form.error?.message ?? (Object.values(form.errors).filter(Boolean).join('. ') || null); } diff --git a/packages/vue/src/runtime/use-form.ts b/packages/vue/src/runtime/use-form.ts index de1ebfe24..3608caf02 100644 --- a/packages/vue/src/runtime/use-form.ts +++ b/packages/vue/src/runtime/use-form.ts @@ -6,6 +6,7 @@ import { isAbortError, isCallSiteActionError, isEqualFormValue, + isFormErrorWithin, parseFormResetArgs, submitAction, type FormResetOptions, @@ -54,7 +55,7 @@ export function useForm( (val) => { for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(val)])) { if (!isEqualFormValue(val[key], dataSnapshot[key])) { - delete errors[key]; + clearNestedErrors(key); } } dataSnapshot = val; @@ -79,6 +80,14 @@ export function useForm( dataSnapshot = cloneFormValue(data); } + function clearNestedErrors(field: string) { + for (const key of Object.keys(errors)) { + if (isFormErrorWithin(key, field)) { + delete errors[key]; + } + } + } + function clearErrors(...fields: ReadonlyArray) { if (fields.length === 0) { for (const key of Object.keys(errors)) { @@ -86,7 +95,7 @@ export function useForm( } } else { for (const field of fields) { - delete errors[field]; + clearNestedErrors(field); } } } diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts index 01dbfaef4..27a067bd4 100644 --- a/packages/vue/test/unit/use-form.test.ts +++ b/packages/vue/test/unit/use-form.test.ts @@ -7,6 +7,7 @@ import { useIslandForm } from '../../src/runtime/use-island-form.ts'; type TestForm = { setError(field: string, message: string): void; + clearErrors(...fields: Array): void; readonly errors: Record; data: Record; hasChanges: boolean; @@ -162,6 +163,37 @@ describe('useForm setError', () => { await renderToString(app); }); + it('clears nested errors below a replaced parent field and a cleared parent', async () => { + const router = { + visit: async () => ({}), + } as unknown as VoidRouter; + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm('/test', { profile: { name: '' }, contacts: [{ email: '' }] }, {}); + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.setError('name', 'Unrelated'); + form.data.profile = { name: 'Alex' }; + expect(form.errors['profile.name']).toBeUndefined(); + expect(form.errors['contacts.0.email']).toBe('Required email'); + form.data.contacts = [{ email: 'alex@example.com' }]; + expect(form.errors).toEqual({ name: 'Unrelated' }); + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.clearErrors('profile'); + expect(form.errors['profile.name']).toBeUndefined(); + expect(form.errors['contacts.0.email']).toBe('Required email'); + form.clearErrors('contacts'); + expect(form.errors).toEqual({ name: 'Unrelated' }); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', router); + await renderToString(app); + }); + it('keeps errors on other fields when one field changes', async () => { const router = { visit: async () => ({}), From 8f80909bf4522271ad4e899bdd95b3730aba4b3b Mon Sep 17 00:00:00 2001 From: 0froq Date: Sat, 21 Nov 2026 09:37:54 +0800 Subject: [PATCH 3/6] docs: describe nested validation error paths in useForm --- docs/guide/pages-routing/actions-and-forms.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index ff46fa30a..8ab50591a 100644 --- a/docs/guide/pages-routing/actions-and-forms.md +++ b/docs/guide/pages-routing/actions-and-forms.md @@ -153,7 +153,7 @@ The types are inferred from your action's `withValidator()` schema in the compan | Property / Method | Purpose | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data` / `setData` | Current form values, typed to match the action's body schema. | -| `errors` | Field-level validation errors, keys typed to body field names. | +| `errors` | Field-level validation errors, keyed by body field and by nested paths such as `profile.name` or `contacts.0.email`. | | `error` | Action error, or `null`. | | `throwOnError` (option) | Set to `false` to keep authentication and server failures in `form.error` instead of throwing them. | | `post`, `put`, `patch`, `delete` | Submit the form with that method. In React these are native form action callbacks. | @@ -163,11 +163,11 @@ The types are inferred from your action's `withValidator()` schema in the compan | `recentlySuccessful` | `true` for 2 seconds after a successful submission. Useful for flash messages. | | `reset(...fields)` | Reset form data to the current defaults (last submitted values after success). Field names autocomplete. Pass `{ initial: true }` first to reset to the values passed to `useForm`. | | `resetOnSuccess` (option) | When `true`, a successful submit resets defaults to the mount-time values, and form data too unless it was edited during the submit. Useful for create forms that should clear after save. | -| `setError(field, message)` | Set a client-side validation error on a field. | -| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. | +| `setError(field, message)` | Set a client-side validation error on a field, including a nested path such as `profile.name`. | +| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. Clearing a parent field also clears the errors of its nested fields. | | `clearError()` | Clear `error`. | -Use `setError()` for client-side validation. Editing a field clears its error automatically. +Use `setError()` for client-side validation. Editing a field clears its error, including the errors of the fields nested below it. For a native React form, use `form.post`, `form.put`, `form.patch`, or `form.delete` as a native form action. For an awaitable mutation, use `action()`. In Vue, Svelte, and Solid, form submissions return `Promise`; catch thrown errors or use your framework's error handling. From e385a941c6c493bb0e31a8de891131b2ea42897e Mon Sep 17 00:00:00 2001 From: 0froq Date: Mon, 23 Nov 2026 08:11:33 +0800 Subject: [PATCH 4/6] fix: keep top-level keys in generic form error types The nested path union is a deferred conditional for an unresolved type parameter, so generic helpers keyed by `keyof T & string` no longer indexed the error map. --- packages/react/test/unit/use-form.typecheck.ts | 11 ++++++++++- packages/void/src/pages/form-presentation.ts | 11 ++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/react/test/unit/use-form.typecheck.ts b/packages/react/test/unit/use-form.typecheck.ts index 08b274d9b..91a9d8d91 100644 --- a/packages/react/test/unit/use-form.typecheck.ts +++ b/packages/react/test/unit/use-form.typecheck.ts @@ -1,6 +1,15 @@ -import { VoidActionError } from 'void/pages-client'; +import { VoidActionError, type FormState } from 'void/pages-client'; import { useForm } from '../../src/runtime/use-form.ts'; +export function checkGenericFieldHelpers( + form: FormState, + field: keyof T & string, +): string | undefined { + form.setError(field, 'Client-side'); + form.clearErrors(field); + return form.errors[field]; +} + declare module 'void/routes' { interface PageActionMap { '/__form-options/notes': { actions: { create: { body: { title: string } } } }; diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index 75348957d..88c4f6761 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -35,8 +35,13 @@ export type FormErrorPath = []> = Depth[ : K | `${K}.${FormErrorPath}`; }[keyof T & string] : never; +/** + * A body field or one of its nested paths. `keyof TData & string` keeps top-level names usable in + * generic callers, where TypeScript cannot resolve the `FormErrorPath` conditional. + */ +type FormFieldPath = FormErrorPath | (keyof TData & string); /** Field-keyed validation messages; a field without an error is absent. */ -export type FormErrors = Partial, string>>; +export type FormErrors = Partial, string>>; /** * How an adapter's apps change `data` and `errors`, following its framework's idiom. * `'in-place'`: apps edit them directly (Vue, Svelte). @@ -55,8 +60,8 @@ export type FormState = FormStatus & Readonly<{ reset(options: FormResetOptions, ...fields: ReadonlyArray): void; reset(...fields: ReadonlyArray): void; - setError(field: FormErrorPath, message: string): void; - clearErrors(...fields: ReadonlyArray>): void; + setError(field: FormFieldPath, message: string): void; + clearErrors(...fields: ReadonlyArray>): void; clearError(): void; }>; /** From 4221430486762c3ffe82c3fe57bc55c51a468593 Mon Sep 17 00:00:00 2001 From: 0froq Date: Mon, 23 Nov 2026 08:11:44 +0800 Subject: [PATCH 5/6] fix: clear only the errors of the changed nested form fields --- docs/guide/pages-routing/actions-and-forms.md | 2 +- packages/react/src/runtime/use-form.ts | 11 ++- packages/react/test/unit/use-form.test.ts | 31 +++---- packages/solid/src/runtime/use-form.ts | 10 ++- packages/solid/test/unit/form-errors.test.ts | 39 ++++++--- .../svelte/src/runtime/use-form.svelte.ts | 19 ++--- packages/svelte/test/unit/use-form.test.ts | 34 +++++--- packages/void/src/pages/client.ts | 2 + packages/void/src/pages/form-presentation.ts | 61 ++++++++++++++ .../void/src/pages/form-value-equality.ts | 2 +- .../void/test/unit/form-presentation.test.ts | 84 ++++++++++++++++++- packages/vue/src/runtime/use-form.ts | 8 +- packages/vue/test/unit/use-form.test.ts | 30 ++++--- 13 files changed, 264 insertions(+), 69 deletions(-) diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index 8ab50591a..dfcf47a46 100644 --- a/docs/guide/pages-routing/actions-and-forms.md +++ b/docs/guide/pages-routing/actions-and-forms.md @@ -167,7 +167,7 @@ The types are inferred from your action's `withValidator()` schema in the compan | `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. Clearing a parent field also clears the errors of its nested fields. | | `clearError()` | Clear `error`. | -Use `setError()` for client-side validation. Editing a field clears its error, including the errors of the fields nested below it. +Use `setError()` for client-side validation. Editing a value clears its error and the errors of the nested values that changed with it. Fields you did not change keep their errors. For a native React form, use `form.post`, `form.put`, `form.patch`, or `form.delete` as a native form action. For an awaitable mutation, use `action()`. In Vue, Svelte, and Solid, form submissions return `Promise`; catch thrown errors or use your framework's error handling. diff --git a/packages/react/src/runtime/use-form.ts b/packages/react/src/runtime/use-form.ts index f9f3ad80a..7a083a229 100644 --- a/packages/react/src/runtime/use-form.ts +++ b/packages/react/src/runtime/use-form.ts @@ -9,6 +9,8 @@ import { } from 'react'; import { VoidActionError, + affectedFormErrorKeys, + changedFormFields, cloneFormValue, getValidationErrors, interpolateRouteParams, @@ -201,13 +203,16 @@ export function useForm( const target = callbackOutcomeRef.current ?? outcome; setErrorEdits((prev) => { const current = resolveOutcomeErrors(target, prev); - const next = omitFormErrors(current, [field]); - if (next === current) { + const affected = affectedFormErrorKeys( + current, + changedFormFields(previousValue, value, field), + ); + if (affected.length === 0) { return prev; } return { ...(prev?.source === target ? prev : { source: target }), - errors: next, + errors: omitFormErrors(current, affected), }; }); }, diff --git a/packages/react/test/unit/use-form.test.ts b/packages/react/test/unit/use-form.test.ts index d95561a12..e2de9ae7d 100644 --- a/packages/react/test/unit/use-form.test.ts +++ b/packages/react/test/unit/use-form.test.ts @@ -23,7 +23,10 @@ declare module 'void/routes' { interface PageActionMap { '/__form-callbacks/notes': { actions: { create: { body: { title: string } } } }; '/__form-nested/contacts': { - body: { profile: { name: string }; contacts: Array<{ email: string }> }; + body: { + profile: { name: string; email: string }; + contacts: Array<{ email: string }>; + }; }; } } @@ -250,13 +253,13 @@ describe('useForm callbacks', () => { expect(formRef.current!.error).toBe(actionError); }); - it('clears nested errors below a replaced parent field and a cleared parent', async () => { + it('clears only the errors of the fields a change touched', async () => { type NestedForm = ReturnType>; const formRef: { current: NestedForm | null } = { current: null }; function App() { formRef.current = useForm('/__form-nested/contacts', { - profile: { name: '' }, - contacts: [{ email: '' }], + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], }); return null; } @@ -264,7 +267,9 @@ describe('useForm callbacks', () => { vi.fn(async () => ({ errors: { 'profile.name': 'Required name', - 'contacts.0.email': 'Required email', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', title: 'Unrelated', }, })), @@ -279,26 +284,22 @@ describe('useForm callbacks', () => { }); await submit(); - expect(form().errors['profile.name']).toBe('Required name'); - expect(form().errors['contacts.0.email']).toBe('Required email'); - await act(async () => { - form().setData('profile', { name: 'Alex' }); + form().setData('profile', { name: 'Alex', email: '' }); }); expect(form().errors['profile.name']).toBeUndefined(); - expect(form().errors['contacts.0.email']).toBe('Required email'); + expect(form().errors['profile.email']).toBe('Required email'); await act(async () => { - form().setData('contacts', [{ email: 'alex@example.com' }]); + form().setData('contacts', [{ email: '' }, { email: 'alex@example.com' }]); }); - expect(form().errors).toEqual({ title: 'Unrelated' }); + expect(form().errors['contacts.0.email']).toBe('First email'); + expect(form().errors['contacts.1.email']).toBeUndefined(); - await submit(); await act(async () => { form().clearErrors('profile'); }); - expect(form().errors['profile.name']).toBeUndefined(); - expect(form().errors['contacts.0.email']).toBe('Required email'); + expect(form().errors).toEqual({ 'contacts.0.email': 'First email', title: 'Unrelated' }); await act(async () => { form().clearErrors('contacts'); diff --git a/packages/solid/src/runtime/use-form.ts b/packages/solid/src/runtime/use-form.ts index 7aa900c2b..a2d689a5a 100644 --- a/packages/solid/src/runtime/use-form.ts +++ b/packages/solid/src/runtime/use-form.ts @@ -2,6 +2,8 @@ import { createSignal, createMemo, useContext } from 'solid-js'; import { createStore, reconcile } from 'solid-js/store'; import { VoidActionError, + affectedFormErrorKeys, + changedFormFields, cloneFormValue, getValidationErrors, interpolateRouteParams, @@ -89,8 +91,14 @@ export function useForm( }); function setData(field: string, value: unknown) { + // The store updates in place, so snapshot the old value before the write. + const previous = cloneFormValue(data[field]); setDataStore(field, value); - clearErrors(field); + const current = errors(); + const affected = affectedFormErrorKeys(current, changedFormFields(previous, value, field)); + if (affected.length > 0) { + replaceErrors(omitFormErrors(current, affected)); + } } function reset(...args: ReadonlyArray) { diff --git a/packages/solid/test/unit/form-errors.test.ts b/packages/solid/test/unit/form-errors.test.ts index 954353029..079272a82 100644 --- a/packages/solid/test/unit/form-errors.test.ts +++ b/packages/solid/test/unit/form-errors.test.ts @@ -66,33 +66,50 @@ describe('useForm router errors', () => { } }); - it('clears nested errors below a replaced parent field and a cleared parent', () => { + it('clears only the errors of the fields a change touched', () => { const { form, dispose } = createForm( { 'profile.name': 'Required name', - 'contacts.0.email': 'Required email', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', name: 'Unrelated', }, - { profile: { name: '' }, contacts: [{ email: '' }] }, + { + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], + }, ); try { + form.setData('profile', { name: 'Alex', email: '' }); expect(form.errors).toEqual({ - 'profile.name': 'Required name', - 'contacts.0.email': 'Required email', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', + name: 'Unrelated', + }); + + form.setData('contacts', [{ email: '' }, { email: 'alex@example.com' }]); + expect(form.errors).toEqual({ + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', name: 'Unrelated', }); form.clearErrors('profile'); - expect(form.errors).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + expect(form.errors).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); form.setError('profile.name', 'Required name'); - form.setData('profile', { name: 'Alex' }); - expect(form.errors).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + expect(form.errors).toEqual({ + 'profile.name': 'Required name', + 'contacts.0.email': 'First email', + name: 'Unrelated', + }); - form.setData('contacts', [{ email: 'alex@example.com' }]); - expect(form.errors).toEqual({ name: 'Unrelated' }); + form.clearErrors('contacts'); + expect(form.errors).toEqual({ 'profile.name': 'Required name', name: 'Unrelated' }); - form.clearErrors('name'); + form.clearErrors(); expect(form.errors).toEqual({}); } finally { dispose(); diff --git a/packages/svelte/src/runtime/use-form.svelte.ts b/packages/svelte/src/runtime/use-form.svelte.ts index 6a76aeb9a..9bdc54096 100644 --- a/packages/svelte/src/runtime/use-form.svelte.ts +++ b/packages/svelte/src/runtime/use-form.svelte.ts @@ -1,6 +1,8 @@ import { getContext, untrack } from 'svelte'; import { VoidActionError, + affectedFormErrorKeys, + changedFormFields, cloneFormValue, getValidationErrors, interpolateRouteParams, @@ -56,25 +58,20 @@ export function useForm( // Read nested values even after an earlier edit, without subscribing to errors. const current = cloneFormValue(data); untrack(() => { - for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(current)])) { - if (!isEqualFormValue(current[key], dataSnapshot[key])) { - for (const errorKey of Object.keys(errors)) { - if (isFormErrorWithin(errorKey, key)) { - delete errors[errorKey]; - } - } - } + for (const key of affectedFormErrorKeys(errors, changedFormFields(dataSnapshot, current))) { + delete errors[key]; } dataSnapshot = current; }); }); // An input handler may validate its new value before the change effect runs. - // Nested error keys snapshot the parent field, which owns the changed value. + // Snapshot the edited value so the effect keeps the error it just set. function snapshotField(field: string) { - const [parent] = field.split('.'); untrack(() => { - dataSnapshot = { ...dataSnapshot, [parent]: cloneFormValue(data[parent]) }; + // A field name that contains a dot is a literal key, not a path below a parent field. + const key = field in data ? field : field.split('.')[0]; + dataSnapshot = { ...dataSnapshot, [key]: cloneFormValue(data[key]) }; }); } diff --git a/packages/svelte/test/unit/use-form.test.ts b/packages/svelte/test/unit/use-form.test.ts index 1fa0593b7..813750c81 100644 --- a/packages/svelte/test/unit/use-form.test.ts +++ b/packages/svelte/test/unit/use-form.test.ts @@ -155,32 +155,46 @@ describe('useForm field errors', () => { expect({ ...form.errors }).toEqual({ name: 'Name invalid' }); }); - it('clears nested errors below an edited parent field and a cleared parent', () => { - const form = mountForm({ profile: { name: '' }, contacts: [{ email: '' }] }); + it('clears only the errors of the fields a change touched', () => { + const form = mountForm({ + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], + }); form.setError('profile.name', 'Required name'); - form.setError('contacts.0.email', 'Required email'); + form.setError('profile.email', 'Required email'); + form.setError('contacts.0.email', 'First email'); + form.setError('contacts.1.email', 'Second email'); form.setError('name', 'Unrelated'); svelte.flushSync(); - form.data.profile = { name: 'Alex' }; + form.data.profile = { name: 'Alex', email: '' }; svelte.flushSync(); - expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + expect(form.errors['profile.name']).toBeUndefined(); + expect(form.errors['profile.email']).toBe('Required email'); - form.data.contacts = [{ email: 'alex@example.com' }]; + form.data.contacts = [{ email: '' }, { email: 'alex@example.com' }]; svelte.flushSync(); - expect({ ...form.errors }).toEqual({ name: 'Unrelated' }); + expect(form.errors['contacts.0.email']).toBe('First email'); + expect(form.errors['contacts.1.email']).toBeUndefined(); - form.setError('profile.name', 'Required name'); - form.setError('contacts.0.email', 'Required email'); form.clearErrors('profile'); svelte.flushSync(); - expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'Required email', name: 'Unrelated' }); + expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); form.clearErrors('contacts'); svelte.flushSync(); expect({ ...form.errors }).toEqual({ name: 'Unrelated' }); }); + it('keeps an error set for a field whose name contains a dot', () => { + const form = mountForm({ 'email.work': '' }); + + form.data['email.work'] = 'alice@example.com'; + form.setError('email.work', 'Invalid email'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'email.work': 'Invalid email' }); + }); + it('clears an error written before the field edit in the same handler', () => { const form = mountForm({ email: '' }); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 47a7d72b2..4997b8b24 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -645,6 +645,8 @@ export function initIslands( } export { + affectedFormErrorKeys, + changedFormFields, formErrorMessage, formRetryMessage, formSubmissionBlocked, diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index 88c4f6761..f76d35e35 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -1,6 +1,7 @@ import type { RouteUrl } from 'void/routes'; import type { VoidActionError } from './action-result.ts'; import type { FormResetOptions } from './form-reset.ts'; +import { isEqualFormValue, isPlainObject } from './form-value-equality.ts'; import type { VisitOptions } from './navigation-engine.ts'; export type FormMethod = 'post' | 'put' | 'patch' | 'delete'; @@ -85,6 +86,66 @@ export type IslandFormState = FormStatus & export function isFormErrorWithin(key: string, field: string): boolean { return key === field || key.startsWith(`${field}.`); } +/** + * Dotted paths of the values that differ between two form value snapshots. `prefix` names the field + * the two values belong to. Only arrays and plain objects are visited, matching `cloneFormValue` + * and `isEqualFormValue`, so a `File`, `Date` or class instance stays one value. + */ +export function changedFormFields( + previous: unknown, + next: unknown, + prefix = '', +): ReadonlyArray { + const changed: Array = []; + collectChangedFormFields(previous, next, prefix, changed); + return changed; +} +function collectChangedFormFields( + previous: unknown, + next: unknown, + prefix: string, + changed: Array, +): void { + if (isEqualFormValue(previous, next)) { + return; + } + if (Array.isArray(previous) && Array.isArray(next)) { + const length = Math.max(previous.length, next.length); + for (let index = 0; index < length; index += 1) { + collectChangedFormFields( + previous[index], + next[index], + joinFormPath(prefix, String(index)), + changed, + ); + } + return; + } + if (isPlainObject(previous) && isPlainObject(next)) { + for (const key of new Set([...Object.keys(previous), ...Object.keys(next)])) { + collectChangedFormFields(previous[key], next[key], joinFormPath(prefix, key), changed); + } + return; + } + if (prefix !== '') { + changed.push(prefix); + } +} +function joinFormPath(prefix: string, key: string): string { + return prefix === '' ? key : `${prefix}.${key}`; +} +/** + * Error keys a change touched: the changed field, the fields below it, and the field that contains + * it. Editing one contact's email keeps the error of another contact. + */ +export function affectedFormErrorKeys( + errors: Readonly>, + changedFields: ReadonlyArray, +): ReadonlyArray { + return Object.keys(errors).filter((key) => + changedFields.some((field) => isFormErrorWithin(key, field) || isFormErrorWithin(field, key)), + ); +} /** * Removes the errors of `fields` and of the nested fields below them, keeping unrelated errors. * Returns the same object when no error matched, so callers can skip an update. diff --git a/packages/void/src/pages/form-value-equality.ts b/packages/void/src/pages/form-value-equality.ts index 363d38461..392012629 100644 --- a/packages/void/src/pages/form-value-equality.ts +++ b/packages/void/src/pages/form-value-equality.ts @@ -1,4 +1,4 @@ -function isPlainObject(value: unknown): value is Record { +export function isPlainObject(value: unknown): value is Record { if (value === null || typeof value !== 'object') { return false; } diff --git a/packages/void/test/unit/form-presentation.test.ts b/packages/void/test/unit/form-presentation.test.ts index 910142197..b0c9a11ff 100644 --- a/packages/void/test/unit/form-presentation.test.ts +++ b/packages/void/test/unit/form-presentation.test.ts @@ -1,8 +1,12 @@ -import { afterEach, expect, it, vi } from 'vite-plus/test'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { VoidActionError } from '../../src/pages/action-result.ts'; import { + affectedFormErrorKeys, + changedFormFields, formErrorMessage, formSubmissionBlocked, + isFormErrorWithin, + omitFormErrors, scheduleFormRetry, } from '../../src/pages/form-presentation.ts'; const error = () => @@ -40,3 +44,81 @@ it('blocks only while pending or until a known retry deadline, without submittin await vi.advanceTimersByTimeAsync(2000); expect(ready).toHaveBeenCalledOnce(); }); + +describe('changedFormFields', () => { + it('returns only the values that changed', () => { + expect( + changedFormFields( + { profile: { name: '', email: '' }, contacts: [{ email: '' }, { email: '' }] }, + { profile: { name: 'Alex', email: '' }, contacts: [{ email: '' }, { email: 'a@b' }] }, + ), + ).toEqual(['profile.name', 'contacts.1.email']); + }); + + it('prefixes the paths with the field the values belong to', () => { + expect(changedFormFields({ name: '' }, { name: 'Alex' }, 'profile')).toEqual(['profile.name']); + }); + + it('reports an added, removed or replaced value as one path', () => { + expect(changedFormFields({ name: '' }, {}, 'profile')).toEqual(['profile.name']); + expect(changedFormFields({}, { name: '' }, 'profile')).toEqual(['profile.name']); + expect(changedFormFields({ name: '' }, null, 'profile')).toEqual(['profile']); + }); + + it('splits arrays by index', () => { + expect(changedFormFields(['a'], ['a', 'b'], 'tags')).toEqual(['tags.1']); + }); + + it('keeps a value that is not an array or plain object whole', () => { + const date = new Date(0); + expect(changedFormFields({ date }, { date }, 'doc')).toEqual([]); + expect(changedFormFields({ date }, { date: new Date(1) }, 'doc')).toEqual(['doc.date']); + }); +}); + +describe('affectedFormErrorKeys', () => { + const errors = { + 'profile.name': 'Required name', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', + profile: 'Profile invalid', + name: 'Unrelated', + }; + + it('keeps the errors of the fields the change did not touch', () => { + expect(affectedFormErrorKeys(errors, ['contacts.1.email'])).toEqual(['contacts.1.email']); + }); + + it('clears the field that contains the changed value', () => { + expect(affectedFormErrorKeys(errors, ['profile.name'])).toEqual(['profile.name', 'profile']); + }); + + it('clears the fields below a replaced value', () => { + expect(affectedFormErrorKeys(errors, ['profile'])).toEqual([ + 'profile.name', + 'profile.email', + 'profile', + ]); + }); +}); + +describe('isFormErrorWithin', () => { + it('matches the field and the fields below it', () => { + expect(isFormErrorWithin('profile', 'profile')).toBe(true); + expect(isFormErrorWithin('profile.name', 'profile')).toBe(true); + expect(isFormErrorWithin('profile.name', 'profileName')).toBe(false); + }); +}); + +describe('omitFormErrors', () => { + it('removes the field and the fields below it', () => { + const errors = { profile: 'Invalid', 'profile.name': 'Required', name: 'Required' }; + expect(omitFormErrors(errors, ['profile'])).toEqual({ name: 'Required' }); + }); + + it('returns the same map when nothing matched', () => { + const errors = { name: 'Required' }; + expect(omitFormErrors(errors, ['profile'])).toBe(errors); + }); +}); diff --git a/packages/vue/src/runtime/use-form.ts b/packages/vue/src/runtime/use-form.ts index 3608caf02..de79a99ba 100644 --- a/packages/vue/src/runtime/use-form.ts +++ b/packages/vue/src/runtime/use-form.ts @@ -1,5 +1,7 @@ import { VoidActionError, + affectedFormErrorKeys, + changedFormFields, cloneFormValue, getValidationErrors, interpolateRouteParams, @@ -53,10 +55,8 @@ export function useForm( watch( () => cloneFormValue(data), (val) => { - for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(val)])) { - if (!isEqualFormValue(val[key], dataSnapshot[key])) { - clearNestedErrors(key); - } + for (const key of affectedFormErrorKeys(errors, changedFormFields(dataSnapshot, val))) { + delete errors[key]; } dataSnapshot = val; }, diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts index 27a067bd4..12b5acd5f 100644 --- a/packages/vue/test/unit/use-form.test.ts +++ b/packages/vue/test/unit/use-form.test.ts @@ -163,27 +163,35 @@ describe('useForm setError', () => { await renderToString(app); }); - it('clears nested errors below a replaced parent field and a cleared parent', async () => { + it('clears only the errors of the fields a change touched', async () => { const router = { visit: async () => ({}), } as unknown as VoidRouter; const app = createSSRApp( defineComponent({ setup() { - const form = useForm('/test', { profile: { name: '' }, contacts: [{ email: '' }] }, {}); + const form = useForm( + '/test', + { profile: { name: '', email: '' }, contacts: [{ email: '' }, { email: '' }] }, + {}, + ); form.setError('profile.name', 'Required name'); - form.setError('contacts.0.email', 'Required email'); + form.setError('profile.email', 'Required email'); + form.setError('contacts.0.email', 'First email'); + form.setError('contacts.1.email', 'Second email'); form.setError('name', 'Unrelated'); - form.data.profile = { name: 'Alex' }; + + form.data.profile = { name: 'Alex', email: '' }; expect(form.errors['profile.name']).toBeUndefined(); - expect(form.errors['contacts.0.email']).toBe('Required email'); - form.data.contacts = [{ email: 'alex@example.com' }]; - expect(form.errors).toEqual({ name: 'Unrelated' }); - form.setError('profile.name', 'Required name'); - form.setError('contacts.0.email', 'Required email'); + expect(form.errors['profile.email']).toBe('Required email'); + + form.data.contacts = [{ email: '' }, { email: 'alex@example.com' }]; + expect(form.errors['contacts.0.email']).toBe('First email'); + expect(form.errors['contacts.1.email']).toBeUndefined(); + form.clearErrors('profile'); - expect(form.errors['profile.name']).toBeUndefined(); - expect(form.errors['contacts.0.email']).toBe('Required email'); + expect(form.errors).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); + form.clearErrors('contacts'); expect(form.errors).toEqual({ name: 'Unrelated' }); return () => h('form'); From 9f3cf5c2b5f3a41560de391c5d139b4f496a2272 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Mon, 23 Nov 2026 09:40:16 +0900 Subject: [PATCH 6/6] Preserve form errors for unchanged fields. --- packages/react/src/runtime/use-form.ts | 23 ++- packages/react/test/unit/use-form.test.ts | 51 +++++++ packages/solid/src/runtime/use-form.ts | 21 ++- packages/solid/test/unit/form-errors.test.ts | 43 ++++++ .../svelte/src/runtime/use-form.svelte.ts | 50 +++---- packages/svelte/test/unit/use-form.test.ts | 43 ++++++ packages/void/src/pages/client.ts | 5 +- packages/void/src/pages/form-presentation.ts | 137 ++++++++++-------- .../void/src/pages/form-value-equality.ts | 10 +- .../void/test/unit/form-presentation.test.ts | 128 +++++++++------- packages/vue/src/runtime/use-form.ts | 27 +--- packages/vue/test/unit/use-form.test.ts | 34 +++++ 12 files changed, 384 insertions(+), 188 deletions(-) diff --git a/packages/react/src/runtime/use-form.ts b/packages/react/src/runtime/use-form.ts index 7a083a229..fa078e31e 100644 --- a/packages/react/src/runtime/use-form.ts +++ b/packages/react/src/runtime/use-form.ts @@ -9,9 +9,9 @@ import { } from 'react'; import { VoidActionError, - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, @@ -194,19 +194,14 @@ export function useForm( const setData = useCallback( (field: string, value: unknown) => { - const previousValue = dataRef.current[field]; - dataRef.current = { ...dataRef.current, [field]: value }; - setDataState(dataRef.current); - if (isEqualFormValue(previousValue, value)) { - return; - } + const previous = dataRef.current; + const next = { ...previous, [field]: value }; + dataRef.current = next; + setDataState(next); const target = callbackOutcomeRef.current ?? outcome; setErrorEdits((prev) => { const current = resolveOutcomeErrors(target, prev); - const affected = affectedFormErrorKeys( - current, - changedFormFields(previousValue, value, field), - ); + const affected = changedFormErrorKeys(current, previous, next); if (affected.length === 0) { return prev; } @@ -241,12 +236,14 @@ export function useForm( const clearErrors = useCallback( (...fields: ReadonlyArray) => { const target = callbackOutcomeRef.current ?? outcome; + const data = dataRef.current; setErrorEdits((prev) => { const base = prev?.source === target ? prev : { source: target }; if (fields.length === 0) { return { ...base, errors: EMPTY_ERRORS }; } - const next = omitFormErrors(resolveOutcomeErrors(target, prev), fields); + const current = resolveOutcomeErrors(target, prev); + const next = omitFormErrors(current, formErrorKeysWithin(current, fields, data)); return { ...base, errors: next }; }); }, diff --git a/packages/react/test/unit/use-form.test.ts b/packages/react/test/unit/use-form.test.ts index e2de9ae7d..75df0caaf 100644 --- a/packages/react/test/unit/use-form.test.ts +++ b/packages/react/test/unit/use-form.test.ts @@ -863,3 +863,54 @@ describe('useForm state derivation and error management', () => { } }); }); + +declare module 'void/routes' { + interface PageActionMap { + '/__form-optional/contacts': { + body: { contacts: Array<{ email: string } | undefined> }; + }; + } +} + +describe('error isolation', () => { + it.each([ + { + name: 'changes one row while an array-level and two row-level errors exist', + initial: [{ email: '' }, { email: '' }], + updated: [{ email: 'fixed@example.com' }, { email: '' }], + initialErrors: { + contacts: 'At least one valid email required', + 'contacts.0.email': 'First email required', + 'contacts.1.email': 'Second email required', + }, + expectedErrors: { 'contacts.1.email': 'Second email required' }, + }, + { + name: 'clears the array-level count error after adding an undefined slot', + initial: [undefined], + updated: [undefined, undefined], + initialErrors: { contacts: 'Add a second row' }, + expectedErrors: {}, + }, + ])('$name', async ({ initial, updated, initialErrors, expectedErrors }) => { + type OptionalForm = ReturnType>; + const formRef: { current: OptionalForm | null } = { current: null }; + function App() { + formRef.current = useForm('/__form-optional/contacts', { contacts: initial }); + return null; + } + const router = routerWithVisit(async () => ({ errors: initialErrors })); + await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App))); + await act(async () => { + startTransition(() => { + formRef.current!.post(new FormData()); + }); + }); + expect(formRef.current!.errors).toEqual(initialErrors); + await act(async () => { + formRef.current!.setData('contacts', updated); + }); + expect(formRef.current!.data.contacts).toEqual(updated); + expect(formRef.current!.errors).toEqual(expectedErrors); + }); +}); diff --git a/packages/solid/src/runtime/use-form.ts b/packages/solid/src/runtime/use-form.ts index a2d689a5a..966a62090 100644 --- a/packages/solid/src/runtime/use-form.ts +++ b/packages/solid/src/runtime/use-form.ts @@ -2,9 +2,9 @@ import { createSignal, createMemo, useContext } from 'solid-js'; import { createStore, reconcile } from 'solid-js/store'; import { VoidActionError, - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, @@ -91,11 +91,15 @@ export function useForm( }); function setData(field: string, value: unknown) { - // The store updates in place, so snapshot the old value before the write. - const previous = cloneFormValue(data[field]); + // The store can merge the new value into the existing object. Snapshot that field + // before the write and compare against what the store actually kept. + const previous = { ...data }; + if (Object.hasOwn(previous, field)) { + previous[field] = cloneFormValue(previous[field]); + } setDataStore(field, value); const current = errors(); - const affected = affectedFormErrorKeys(current, changedFormFields(previous, value, field)); + const affected = changedFormErrorKeys(current, previous, data); if (affected.length > 0) { replaceErrors(omitFormErrors(current, affected)); } @@ -114,7 +118,12 @@ export function useForm( } function clearErrors(...fields: ReadonlyArray) { - replaceErrors(fields.length === 0 ? {} : omitFormErrors(errors(), fields)); + const current = errors(); + replaceErrors( + fields.length === 0 + ? {} + : omitFormErrors(current, formErrorKeysWithin(current, fields, data)), + ); } function setFieldError(field: string, message: string) { diff --git a/packages/solid/test/unit/form-errors.test.ts b/packages/solid/test/unit/form-errors.test.ts index 079272a82..cdc19bf15 100644 --- a/packages/solid/test/unit/form-errors.test.ts +++ b/packages/solid/test/unit/form-errors.test.ts @@ -10,6 +10,7 @@ vi.mock('solid-js/store', () => ); type TestForm = { + data: Readonly>; errors: Record; setData(field: string, value: unknown): void; setError(field: string, message: string): void; @@ -128,3 +129,45 @@ describe('useForm router errors', () => { } }); }); + +it('keeps an untouched row error when clearing its parent array error', () => { + const { form, dispose } = createForm( + { + contacts: 'At least one valid email required', + 'contacts.0.email': 'First email required', + 'contacts.1.email': 'Second email required', + }, + { contacts: [{ email: '' }, { email: '' }] }, + ); + try { + form.setData('contacts', [{ email: 'fixed@example.com' }, { email: '' }]); + expect(form.errors).toEqual({ 'contacts.1.email': 'Second email required' }); + } finally { + dispose(); + } +}); + +it('clears an array count error after adding an undefined entry', () => { + const { form, dispose } = createForm({ contacts: 'Add a second row' }, { contacts: [undefined] }); + try { + form.setData('contacts', [undefined, undefined]); + expect(form.data.contacts).toEqual([undefined, undefined]); + expect(form.errors).toEqual({}); + } finally { + dispose(); + } +}); + +it('keeps a nested error for an optional key preserved by the store merge', () => { + const { form, dispose } = createForm( + { 'profile.nickname': 'Nickname unavailable' }, + { profile: { name: '', nickname: 'Reserved name' } }, + ); + try { + form.setData('profile', { name: 'Alex' }); + expect(form.data.profile).toEqual({ name: 'Alex', nickname: 'Reserved name' }); + expect(form.errors).toEqual({ 'profile.nickname': 'Nickname unavailable' }); + } finally { + dispose(); + } +}); diff --git a/packages/svelte/src/runtime/use-form.svelte.ts b/packages/svelte/src/runtime/use-form.svelte.ts index 9bdc54096..b40a7c2be 100644 --- a/packages/svelte/src/runtime/use-form.svelte.ts +++ b/packages/svelte/src/runtime/use-form.svelte.ts @@ -1,15 +1,14 @@ import { getContext, untrack } from 'svelte'; import { VoidActionError, - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, isCallSiteActionError, isEqualFormValue, - isFormErrorWithin, parseFormResetArgs, submitAction, type FormResetOptions, @@ -54,34 +53,32 @@ export function useForm( let latestRequestId = 0; let dataSnapshot = cloneFormValue(initialDefaults); + function clearEditedErrors(current: Record) { + for (const key of changedFormErrorKeys(errors, dataSnapshot, current)) { + delete errors[key]; + } + dataSnapshot = current; + } + $effect(() => { // Read nested values even after an earlier edit, without subscribing to errors. const current = cloneFormValue(data); - untrack(() => { - for (const key of affectedFormErrorKeys(errors, changedFormFields(dataSnapshot, current))) { - delete errors[key]; - } - dataSnapshot = current; - }); + untrack(() => clearEditedErrors(current)); }); - // An input handler may validate its new value before the change effect runs. - // Snapshot the edited value so the effect keeps the error it just set. - function snapshotField(field: string) { - untrack(() => { - // A field name that contains a dot is a literal key, not a path below a parent field. - const key = field in data ? field : field.split('.')[0]; - dataSnapshot = { ...dataSnapshot, [key]: cloneFormValue(data[key]) }; - }); + // An input handler can validate before the effect runs. Clear older errors for + // pending edits before writing the new one. + function clearPendingEditErrors() { + untrack(() => clearEditedErrors(cloneFormValue(data))); } - // Handlers may also write `form.errors.field` directly, which needs the same snapshot. + // Handlers may also write `form.errors.field` directly. // The view is derived because setError and clearErrors replace `errors`. const errorsView = $derived( new Proxy(errors, { set(target, field, message) { if (typeof field === 'string') { - snapshotField(field); + clearPendingEditErrors(); } return Reflect.set(target, field, message); }, @@ -109,18 +106,14 @@ export function useForm( if (fields.length === 0) { errors = {}; } else { - for (const field of fields) { - for (const key of Object.keys(errors)) { - if (isFormErrorWithin(key, field)) { - delete errors[key]; - } - } + for (const key of formErrorKeysWithin(errors, fields, data)) { + delete errors[key]; } } } function setError(field: string, message: string) { - snapshotField(field); + clearPendingEditErrors(); errors = { ...errors, [field]: message }; } @@ -164,9 +157,8 @@ export function useForm( ? getValidationErrors(result.error.body) : null; if (validationErrors) { - for (const [field, message] of Object.entries(validationErrors)) { - setError(field, message); - } + clearPendingEditErrors(); + errors = { ...errors, ...validationErrors }; } else { error = result.error; } diff --git a/packages/svelte/test/unit/use-form.test.ts b/packages/svelte/test/unit/use-form.test.ts index 813750c81..7f4b28bbb 100644 --- a/packages/svelte/test/unit/use-form.test.ts +++ b/packages/svelte/test/unit/use-form.test.ts @@ -432,3 +432,46 @@ describe('useIslandForm edits made during a submit', () => { expect(form.data.title).toBe('Sent'); }); }); + +it('clears the array-level count error after adding an undefined slot', () => { + const form = mountForm({ contacts: [undefined] }); + form.setError('contacts', 'Add a second row'); + (form.data.contacts as Array).push(undefined); + svelte.flushSync(); + expect((form.data.contacts as Array).length).toBe(2); + expect(form.errors.contacts).toBeUndefined(); +}); + +it('clears the object-level error after removing an undefined key', () => { + const form = mountForm({ profile: { option: undefined } }); + form.setError('profile', 'Remove the option field'); + delete (form.data.profile as Record).option; + svelte.flushSync(); + expect(Object.hasOwn(form.data.profile as object, 'option')).toBe(false); + expect(form.errors.profile).toBeUndefined(); +}); + +it('clears stale errors for other edits in the same batch as validation', () => { + const form = mountForm({ contacts: [{ email: '' }, { email: '' }] }); + form.setError('contacts.0.email', 'First email required'); + const contacts = form.data.contacts as Array<{ email: string }>; + contacts[0].email = 'first@example.com'; + contacts[1].email = 'invalid'; + form.setError('contacts.1.email', 'Second email invalid'); + svelte.flushSync(); + + expect({ ...form.errors }).toEqual({ 'contacts.1.email': 'Second email invalid' }); +}); + +it('preserves a separate literal dotted error when editing or clearing its prefix', () => { + const form = mountForm({ email: '', 'email.work': '' }); + form.setError('email', 'Personal email is required'); + form.setError('email.work', 'Work email is required'); + form.data.email = 'new@example.com'; + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'email.work': 'Work email is required' }); + + form.setError('email', 'Invalid email'); + form.clearErrors('email'); + expect({ ...form.errors }).toEqual({ 'email.work': 'Work email is required' }); +}); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 4997b8b24..115bebe23 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -645,12 +645,11 @@ export function initIslands( } export { - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, + formErrorKeysWithin, formErrorMessage, formRetryMessage, formSubmissionBlocked, - isFormErrorWithin, omitFormErrors, scheduleFormRetry, type FormErrorPath, diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index f76d35e35..64ae4b650 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -82,82 +82,95 @@ export type IslandFormState = FormStatus & delete(url: RouteUrl): Promise; }>; -/** Whether an error key names `field` or a nested field below it, such as `profile.name`. */ -export function isFormErrorWithin(key: string, field: string): boolean { - return key === field || key.startsWith(`${field}.`); +function hasFormField(value: unknown, field: string): value is Record { + return (isPlainObject(value) || Array.isArray(value)) && Object.hasOwn(value, field); } -/** - * Dotted paths of the values that differ between two form value snapshots. `prefix` names the field - * the two values belong to. Only arrays and plain objects are visited, matching `cloneFormValue` - * and `isEqualFormValue`, so a `File`, `Date` or class instance stays one value. - */ -export function changedFormFields( - previous: unknown, - next: unknown, - prefix = '', -): ReadonlyArray { - const changed: Array = []; - collectChangedFormFields(previous, next, prefix, changed); - return changed; -} -function collectChangedFormFields( - previous: unknown, - next: unknown, - prefix: string, - changed: Array, -): void { - if (isEqualFormValue(previous, next)) { - return; + +// A literal key can contain dots. Prefer the longest own key before treating dots as path +// separators. Check both snapshots so deleting a literal key still identifies the same field. +function formValuePath(field: string, previous: unknown, next = previous): Array { + const path: Array = []; + for (;;) { + let key = field; + while (!hasFormField(previous, key) && !hasFormField(next, key)) { + const dot = key.lastIndexOf('.'); + if (dot === -1) { + break; + } + key = key.slice(0, dot); + } + path.push(key); + if (key === field) { + return path; + } + previous = hasFormField(previous, key) ? previous[key] : undefined; + next = hasFormField(next, key) ? next[key] : undefined; + field = field.slice(key.length + 1); } - if (Array.isArray(previous) && Array.isArray(next)) { - const length = Math.max(previous.length, next.length); - for (let index = 0; index < length; index += 1) { - collectChangedFormFields( - previous[index], - next[index], - joinFormPath(prefix, String(index)), - changed, +} + +function formValueChanged(previous: unknown, next: unknown, path: ReadonlyArray): boolean { + for (const key of path) { + if (Object.is(previous, next)) { + return false; + } + if (!hasFormField(previous, key)) { + if (hasFormField(next, key)) { + return true; + } + // Replacing a container invalidates descendant errors even when the + // specific field was missing, for example a required field in an empty object. + return !( + (isPlainObject(previous) && isPlainObject(next)) || + (Array.isArray(previous) && Array.isArray(next)) ); } - return; - } - if (isPlainObject(previous) && isPlainObject(next)) { - for (const key of new Set([...Object.keys(previous), ...Object.keys(next)])) { - collectChangedFormFields(previous[key], next[key], joinFormPath(prefix, key), changed); + if (!hasFormField(next, key)) { + return true; } - return; + previous = previous[key]; + next = next[key]; } - if (prefix !== '') { - changed.push(prefix); - } -} -function joinFormPath(prefix: string, key: string): string { - return prefix === '' ? key : `${prefix}.${key}`; + return !isEqualFormValue(previous, next); } -/** - * Error keys a change touched: the changed field, the fields below it, and the field that contains - * it. Editing one contact's email keeps the error of another contact. - */ -export function affectedFormErrorKeys( + +/** The exact error keys whose field values changed, including affected parent fields. */ +export function changedFormErrorKeys( errors: Readonly>, - changedFields: ReadonlyArray, -): ReadonlyArray { + previous: unknown, + next: unknown, +): Array { return Object.keys(errors).filter((key) => - changedFields.some((field) => isFormErrorWithin(key, field) || isFormErrorWithin(field, key)), + formValueChanged(previous, next, formValuePath(key, previous, next)), ); } -/** - * Removes the errors of `fields` and of the nested fields below them, keeping unrelated errors. - * Returns the same object when no error matched, so callers can skip an update. - */ + +/** The error keys on explicitly cleared fields and their descendants. */ +export function formErrorKeysWithin( + errors: Readonly>, + fields: ReadonlyArray, + data: unknown, +): Array { + const paths = fields.map((field) => formValuePath(field, data)); + return Object.keys(errors).filter((key) => { + const path = formValuePath(key, data); + return paths.some((parent) => parent.every((part, index) => part === path[index])); + }); +} + +/** Remove only the selected error keys. */ export function omitFormErrors( errors: Record, - fields: ReadonlyArray, + keys: ReadonlyArray, ): Record { - const kept = Object.entries(errors).filter( - ([key]) => !fields.some((field) => isFormErrorWithin(key, field)), - ); - return kept.length === Object.keys(errors).length ? errors : Object.fromEntries(kept); + if (keys.length === 0) { + return errors; + } + const next = { ...errors }; + for (const key of keys) { + delete next[key]; + } + return next; } export function formErrorMessage(form: Pick): string | null { return form.error?.message ?? (Object.values(form.errors).filter(Boolean).join('. ') || null); diff --git a/packages/void/src/pages/form-value-equality.ts b/packages/void/src/pages/form-value-equality.ts index 392012629..baeff5c37 100644 --- a/packages/void/src/pages/form-value-equality.ts +++ b/packages/void/src/pages/form-value-equality.ts @@ -17,7 +17,15 @@ export function isEqualFormValue(a: unknown, b: unknown): boolean { return false; } - return a.every((value, index) => isEqualFormValue(value, b[index])); + for (let index = 0; index < a.length; index += 1) { + if ( + Object.hasOwn(a, index) !== Object.hasOwn(b, index) || + !isEqualFormValue(a[index], b[index]) + ) { + return false; + } + } + return true; } if (isPlainObject(a) || isPlainObject(b)) { diff --git a/packages/void/test/unit/form-presentation.test.ts b/packages/void/test/unit/form-presentation.test.ts index b0c9a11ff..70dacf4e3 100644 --- a/packages/void/test/unit/form-presentation.test.ts +++ b/packages/void/test/unit/form-presentation.test.ts @@ -1,11 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { VoidActionError } from '../../src/pages/action-result.ts'; import { - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, formErrorMessage, formSubmissionBlocked, - isFormErrorWithin, + formErrorKeysWithin, omitFormErrors, scheduleFormRetry, } from '../../src/pages/form-presentation.ts'; @@ -45,80 +44,101 @@ it('blocks only while pending or until a known retry deadline, without submittin expect(ready).toHaveBeenCalledOnce(); }); -describe('changedFormFields', () => { - it('returns only the values that changed', () => { +describe('changedFormErrorKeys', () => { + const errors = { + contacts: 'More contacts required', + 'contacts.0.email': 'First email invalid', + 'contacts.1.email': 'Second email invalid', + 'contacts.1.name': 'Second name required', + }; + const twoContacts = { contacts: [{ email: '' }, { email: '', name: '' }] }; + + it('selects the changed child and its ancestor but keeps unchanged siblings', () => { expect( - changedFormFields( - { profile: { name: '', email: '' }, contacts: [{ email: '' }, { email: '' }] }, - { profile: { name: 'Alex', email: '' }, contacts: [{ email: '' }, { email: 'a@b' }] }, - ), - ).toEqual(['profile.name', 'contacts.1.email']); + changedFormErrorKeys(errors, twoContacts, { + contacts: [{ email: 'valid@example.com' }, { email: '', name: '' }], + }), + ).toEqual(['contacts', 'contacts.0.email']); }); - it('prefixes the paths with the field the values belong to', () => { - expect(changedFormFields({ name: '' }, { name: 'Alex' }, 'profile')).toEqual(['profile.name']); + it('selects the descendants of a removed row', () => { + expect(changedFormErrorKeys(errors, twoContacts, { contacts: [{ email: '' }] })).toEqual([ + 'contacts', + 'contacts.1.email', + 'contacts.1.name', + ]); }); - it('reports an added, removed or replaced value as one path', () => { - expect(changedFormFields({ name: '' }, {}, 'profile')).toEqual(['profile.name']); - expect(changedFormFields({}, { name: '' }, 'profile')).toEqual(['profile.name']); - expect(changedFormFields({ name: '' }, null, 'profile')).toEqual(['profile']); + it('clears a missing descendant when its container is replaced', () => { + const errors = { 'profile.name': 'Required' }; + expect(changedFormErrorKeys(errors, { profile: {} }, { profile: null })).toEqual([ + 'profile.name', + ]); + expect(changedFormErrorKeys(errors, { profile: {} }, { profile: { email: '' } })).toEqual([]); }); - it('splits arrays by index', () => { - expect(changedFormFields(['a'], ['a', 'b'], 'tags')).toEqual(['tags.1']); + it('keeps a literal dotted field separate from a nested path', () => { + const before = { email: { personal: '' }, 'email.work': '' }; + const errors = { 'email.personal': 'Invalid', 'email.work': 'Invalid' }; + expect( + changedFormErrorKeys(errors, before, { + ...before, + email: { personal: 'valid@example.com' }, + }), + ).toEqual(['email.personal']); + expect(changedFormErrorKeys(errors, before, { email: before.email })).toEqual(['email.work']); + }); + + it('treats undefined fields and array entries as present', () => { + const before = { profile: { nickname: undefined }, contacts: [undefined] }; + expect( + changedFormErrorKeys( + { profile: 'Invalid', 'profile.nickname': 'Invalid', contacts: 'Too short' }, + before, + { profile: {}, contacts: [undefined, undefined] }, + ), + ).toEqual(['profile', 'profile.nickname', 'contacts']); + expect( + changedFormErrorKeys( + { contacts: 'Invalid', 'contacts.0': 'Invalid' }, + { contacts: new Array(1) }, + { contacts: [undefined] }, + ), + ).toEqual(['contacts', 'contacts.0']); }); - it('keeps a value that is not an array or plain object whole', () => { + it('keeps a non-plain object whole', () => { const date = new Date(0); - expect(changedFormFields({ date }, { date }, 'doc')).toEqual([]); - expect(changedFormFields({ date }, { date: new Date(1) }, 'doc')).toEqual(['doc.date']); + const errors = { date: 'Invalid date' }; + expect(changedFormErrorKeys(errors, { date }, { date })).toEqual([]); + expect(changedFormErrorKeys(errors, { date }, { date: new Date(1) })).toEqual(['date']); }); }); -describe('affectedFormErrorKeys', () => { - const errors = { - 'profile.name': 'Required name', - 'profile.email': 'Required email', - 'contacts.0.email': 'First email', - 'contacts.1.email': 'Second email', - profile: 'Profile invalid', - name: 'Unrelated', - }; +describe('formErrorKeysWithin', () => { + const data = { email: { personal: '' }, 'email.work': '' }; + const errors = { email: 'Invalid', 'email.personal': 'Required', 'email.work': 'Required' }; - it('keeps the errors of the fields the change did not touch', () => { - expect(affectedFormErrorKeys(errors, ['contacts.1.email'])).toEqual(['contacts.1.email']); + it('selects a parent and its descendants, preserving flat dotted fields', () => { + expect(formErrorKeysWithin(errors, ['email'], data)).toEqual(['email', 'email.personal']); + expect(formErrorKeysWithin(errors, ['email.work'], data)).toEqual(['email.work']); }); - it('clears the field that contains the changed value', () => { - expect(affectedFormErrorKeys(errors, ['profile.name'])).toEqual(['profile.name', 'profile']); - }); - - it('clears the fields below a replaced value', () => { - expect(affectedFormErrorKeys(errors, ['profile'])).toEqual([ + it('finds descendant errors for a missing optional parent', () => { + expect(formErrorKeysWithin({ 'profile.name': 'Required' }, ['profile'], {})).toEqual([ 'profile.name', - 'profile.email', - 'profile', ]); }); }); -describe('isFormErrorWithin', () => { - it('matches the field and the fields below it', () => { - expect(isFormErrorWithin('profile', 'profile')).toBe(true); - expect(isFormErrorWithin('profile.name', 'profile')).toBe(true); - expect(isFormErrorWithin('profile.name', 'profileName')).toBe(false); - }); -}); - describe('omitFormErrors', () => { - it('removes the field and the fields below it', () => { - const errors = { profile: 'Invalid', 'profile.name': 'Required', name: 'Required' }; - expect(omitFormErrors(errors, ['profile'])).toEqual({ name: 'Required' }); + const errors = { profile: 'Invalid', 'profile.name': 'Required' }; + + it('removes the exact keys selected for an edit', () => { + expect(omitFormErrors(errors, ['profile'])).toEqual({ 'profile.name': 'Required' }); }); - it('returns the same map when nothing matched', () => { - const errors = { name: 'Required' }; - expect(omitFormErrors(errors, ['profile'])).toBe(errors); + it('returns the same map with no keys to remove', () => { + expect(omitFormErrors(errors, [])).toBe(errors); }); }); diff --git a/packages/vue/src/runtime/use-form.ts b/packages/vue/src/runtime/use-form.ts index de79a99ba..4d2688935 100644 --- a/packages/vue/src/runtime/use-form.ts +++ b/packages/vue/src/runtime/use-form.ts @@ -1,14 +1,13 @@ import { VoidActionError, - affectedFormErrorKeys, - changedFormFields, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, isCallSiteActionError, isEqualFormValue, - isFormErrorWithin, parseFormResetArgs, submitAction, type FormResetOptions, @@ -55,7 +54,7 @@ export function useForm( watch( () => cloneFormValue(data), (val) => { - for (const key of affectedFormErrorKeys(errors, changedFormFields(dataSnapshot, val))) { + for (const key of changedFormErrorKeys(errors, dataSnapshot, val)) { delete errors[key]; } dataSnapshot = val; @@ -80,23 +79,11 @@ export function useForm( dataSnapshot = cloneFormValue(data); } - function clearNestedErrors(field: string) { - for (const key of Object.keys(errors)) { - if (isFormErrorWithin(key, field)) { - delete errors[key]; - } - } - } - function clearErrors(...fields: ReadonlyArray) { - if (fields.length === 0) { - for (const key of Object.keys(errors)) { - delete errors[key]; - } - } else { - for (const field of fields) { - clearNestedErrors(field); - } + const keys = + fields.length === 0 ? Object.keys(errors) : formErrorKeysWithin(errors, fields, data); + for (const key of keys) { + delete errors[key]; } } diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts index 12b5acd5f..0a30f157a 100644 --- a/packages/vue/test/unit/use-form.test.ts +++ b/packages/vue/test/unit/use-form.test.ts @@ -460,3 +460,37 @@ describe('useIslandForm edits made during a submit', () => { expect(form.data.title).toBe('Sent'); }); }); + +it('clears the array-level count error after adding an undefined slot', async () => { + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm('/test', { contacts: [undefined] }); + form.setError('contacts', 'Add a second row'); + (form.data.contacts as Array).push(undefined); + expect((form.data.contacts as Array).length).toBe(2); + expect(form.errors.contacts).toBeUndefined(); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', {}); + await renderToString(app); +}); + +it('clears the object-level error after removing an undefined key', async () => { + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm('/test', { profile: { option: undefined } }); + form.setError('profile', 'Remove the option field'); + delete (form.data.profile as Record).option; + expect(Object.hasOwn(form.data.profile as object, 'option')).toBe(false); + expect(form.errors.profile).toBeUndefined(); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', {}); + await renderToString(app); +});