Map refined error to multiple fields #2041
Replies: 4 comments 2 replies
-
Cannot find name 'MySchema'. can you please send a full reproducible example? |
Beta Was this translation helpful? Give feedback.
1 reply
-
Is this what you are looking for? const schema = z.object( {
product: z.object( {
pages: z.number(),
} ),
positions: z.object( {
page: z.number(),
} ).array(),
} ).transform(
( data, ctx ) => {
const { product: { pages }, positions } = data
const failedPositionIndexes = positions.reduce(
( indexes, { page }, index ) => page > pages
? [ ...indexes, index ]
: indexes,
[] as number[]
)
if ( failedPositionIndexes )
failedPositionIndexes.forEach( ( index ) => ctx.addIssue( {
code: 'custom',
message: `Product has only ${ pages } page${ pages != 1 ? 's' : '' }`,
path: [ 'positions', index, 'page' ],
} ) )
return data
}
)
const result = schema.safeParse( {
product: {
pages: 3,
},
positions: [
{ page: 1 },
{ page: 2 },
{ page: 3 },
{ page: 4 },
{ page: 5 },
],
} )
!result.success && console.log( result.error.issues )
// [
// {
// code: 'custom',
// message: 'Product has only 3 pages',
// path: [ 'positions', 3, 'page' ]
// },
// {
// code: 'custom',
// message: 'Product has only 3 pages',
// path: [ 'positions', 4, 'page' ]
// }
// ] If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JacobWeisenburger
-
@JacobWeisenburger this has helped me a great deal, thank you for the idea |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am validating an array and was wondering if there is a way to map an error to multiple items (all that fail the validation).
I am trying this:
Passing an array to
path
joins all the items to a nested path string. But is there a way to actually mark multiple fields with a refinement?Beta Was this translation helpful? Give feedback.
All reactions