Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/guide/pages-routing/actions-and-forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -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<void>`; catch thrown errors or use your framework's error handling.

Expand Down
11 changes: 4 additions & 7 deletions packages/react/src/runtime/use-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
isAbortError,
isCallSiteActionError,
isEqualFormValue,
omitFormErrors,
parseFormResetArgs,
submitAction,
type FormResetOptions,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 };
});
},
Expand Down
59 changes: 59 additions & 0 deletions packages/react/test/unit/use-form.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }> };
};
}
}

Expand Down Expand Up @@ -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<typeof useForm<'/__form-nested/contacts'>>;
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: '[email protected]' }]);
});
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(
Expand Down
21 changes: 21 additions & 0 deletions packages/react/test/unit/use-form.typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
11 changes: 2 additions & 9 deletions packages/solid/src/runtime/use-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
isAbortError,
isCallSiteActionError,
isEqualFormValue,
omitFormErrors,
parseFormResetArgs,
submitAction,
type FormResetOptions,
Expand Down Expand Up @@ -105,15 +106,7 @@ export function useForm(
}

function clearErrors(...fields: ReadonlyArray<string>) {
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) {
Expand Down
45 changes: 39 additions & 6 deletions packages/solid/test/unit/form-errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ const useForm = typedUseForm as unknown as (
defaults: Record<string, unknown>,
) => TestForm;

function createForm() {
const [serverErrors, setServerErrors] = createSignal({
email: 'Invalid email',
name: 'Required',
});
function createForm(
server: Record<string, string> = { email: 'Invalid email', name: 'Required' },
defaults: Record<string, unknown> = { 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;
},
});
Expand Down Expand Up @@ -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: '[email protected]' }]);
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 {
Expand Down
21 changes: 21 additions & 0 deletions packages/solid/test/unit/form-errors.typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]' }]);
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');
Expand Down
17 changes: 14 additions & 3 deletions packages/svelte/src/runtime/use-form.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isAbortError,
isCallSiteActionError,
isEqualFormValue,
isFormErrorWithin,
parseFormResetArgs,
submitAction,
type FormResetOptions,
Expand Down Expand Up @@ -57,17 +58,23 @@ 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;
});
});

// 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]) };
});
}

Expand Down Expand Up @@ -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];
}
}
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions packages/svelte/test/unit/form-errors.typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
Loading