Skip to content

Commit

Permalink
fix: Set top-level form error path (#43)
Browse files Browse the repository at this point in the history
* Use empty path for top-level form errors

* Add tests
  • Loading branch information
evaogbe authored Dec 3, 2024
1 parent a634976 commit 2cc0dda
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 4 deletions.
8 changes: 4 additions & 4 deletions parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ export function parseWithValibot<

return {
error: result.issues.reduce<Record<string, string[]>>((result, e) => {
const name = e.path
? // @ts-expect-error
formatPaths(e.path.map((d) => d.key as string | number))
: (e.input as string | number);
const name = formatPaths(
// @ts-expect-error
e.path?.map((d) => d.key as string | number) ?? [],
);

result[name] = [...(result[name] ?? []), e.message];

Expand Down
23 changes: 23 additions & 0 deletions tests/coercion/schema/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,27 @@ describe("object", () => {
},
});
});

test("should fail with check on object", () => {
const schema = pipe(
object({
key1: string(),
key2: string(),
}),
check(({ key1, key2 }) => key1 === key2, "keys must match"),
);

const input = createFormData("key1", "foo");
input.append("key2", "bar");

const errorOutput = parseWithValibot(input, {
schema,
});

expect(errorOutput).toMatchObject({
error: {
"": ["keys must match"],
},
});
});
});
23 changes: 23 additions & 0 deletions tests/coercion/schema/objectAsync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,27 @@ describe("objectAsync", () => {
},
});
});

test("should fail with check on object", async () => {
const schema = pipeAsync(
objectAsync({
key1: string(),
key2: string(),
}),
checkAsync(({ key1, key2 }) => key1 === key2, "keys must match"),
);

const input = createFormData("key1", "foo");
input.append("key2", "bar");

const errorOutput = await parseWithValibot(input, {
schema,
});

expect(errorOutput).toMatchObject({
error: {
"": ["keys must match"],
},
});
});
});

0 comments on commit 2cc0dda

Please sign in to comment.