<

Stuck on the path in zod's refine

I was using zod's refine, but I couldn't understand how to use the path at all, and I got stuck for about an hour, so I'll leave it as a memo.

Background

I was writing validation logic using zod. I had to refer to multiple fields in the validation, so I was using refine.

https://github.com/colinhacks/zod#refine

path

I'll show you the sample code below.

import { z } from "zod";

const schema = z.object({
  a: z
    .object({
      first: z.string(),
    })
    .refine(({ first }) => first === "first", {
      path: ["b"],
    }),
});

I defined refine on an object called a. I defined ['b'] in the path of the second argument of refine.

Let's test the schema.

import test from "tape";

test("invalid", (t) => {
  // Act
  const data = schema.safeParse({
    a: {
      first: "BUG",
    },
  });

  // Assert
  t.deepEqual(data.error.issues[0].path, ["a", "b"]);
  t.end();
});

The path of the error (issue) will be ['a', 'b']. It's very obvious, but that's it. (laughs)

I also left it on stackblitz.

https://stackblitz.com/edit/nodemon-fkzaw5?file=index.js

The description of the path on zod's github says appended to error path.

If it was helpful, support me with a ☕!

Share

Related tags