1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00
Files
til/zod/set-custom-error-message-for-nonempty-array.md

1.3 KiB

Set Custom Error Message For Nonempty Array

Let's say we have the following schema that represents a team:

const TeamSchema = z.object({
  name: z.string(),
  members: z.array(
    z.object({ firstName: z.string(), lastName: z.string() })
  )
})

If we want to enforce that a team must contain at least one member in order to be valid, we can chain the nonempty function on the members array.

const TeamSchema = z.object({
  name: z.string(),
  members: z.array(
    z.object({ firstName: z.string(), lastName: z.string() })
  ).nonempty()
})

Then we can set a custom error message for when that nonempty requirement is violated by adding an object argument with a message:

const TeamSchema = z.object({
  name: z.string(),
  members: z.array(
    z.object({ firstName: z.string(), lastName: z.string() })
  ).nonempty({
    message: 'A team must contain at least one member'
  })
})

Here is that schema in action, not the message in the error:

TeamSchema.parse({ name: 'A-Team', members: [] })
// Error: [{
//   "code": "too_small",
//   "minimum": 1,
//   "type": "array",
//   "inclusive": true,
//   "exact": false,
//   "message": "A team must contain at least one member",
//   "path": [
//     "members"
//   ]
// }]

source