Zod one or more values from an array

Thanks in advance, my mind has gone blank and I just cannot think at this point. How can I say with zod I want to have at least one value of these array of possible values passed through. So basically a multi select picklist.
4 Replies
Neto
Neto3y ago
probably with refine
import { z } from 'zod'

const arr = ['b']

const schema = z
.array(z.string())
.refine((val) => val.every((v) => arr.includes(v)), {
message: 'Array element not in valid array'
})

const payload = ['b']

const result = schema.safeParse(payload)

console.log(result)
import { z } from 'zod'

const arr = ['b']

const schema = z
.array(z.string())
.refine((val) => val.every((v) => arr.includes(v)), {
message: 'Array element not in valid array'
})

const payload = ['b']

const result = schema.safeParse(payload)

console.log(result)
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Neto
Neto3y ago
with valid payload
{ success: true, data: [ "b" ] }
{ success: true, data: [ "b" ] }
with invalid payload
{
"success": false,
"error": {
"issues": [
{
"code": "custom",
"message": "Array element not in valid array",
"path": []
}
],
"name": "ZodError"
}
}
{
"success": false,
"error": {
"issues": [
{
"code": "custom",
"message": "Array element not in valid array",
"path": []
}
],
"name": "ZodError"
}
}
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server