colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
32.86k stars 1.14k forks source link

Zod refine is not working #3548

Open zack990420 opened 3 months ago

zack990420 commented 3 months ago

I have tried this two method of refine, but both of it are not working.

image

pedramp commented 3 months ago

It does work just fine for me. tested with zod 3.23.8v

const z = require('zod');

const validation = z.object({
    nationality: z.string().refine((val) => val === 'X', {message: 'is not X', path: ['path-x']}),
    nric: z.string().optional()
}).refine((data) => data.nationality === 'X', {message: 'is not X(second refine)', path: ['path-x']})

const result = validation.parse({ nationality: 'X' })
console.log(result); // { nationality: 'X' }

and for error:

const result = validation.parse({ nationality: 'xyz' })
console.log(result);

ZodError: [
  {
    "code": "custom",
    "message": "is not X",
    "path": [
      "nationality",
      "path-x"
    ]
  },
  {
    "code": "custom",
    "message": "is not X(second refine)",
    "path": [
      "path-x"
    ]
  }
]