Refine for object when using zod not work without optional #2071
-
My Codesandbox link: https://codesandbox.io/s/react-typescript-forked-uktywz Can anyone help me, why the validation for "End date must be after start date" not work when I remove optional() on the something key of zod schema? The problem also occurs when something is an array. |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Feb 21, 2023
Replies: 1 comment 3 replies
-
Everything seems to be working as expected for me. const schema = z.object( {
something: z.object( { key: z.string() } ),
name: z.string().min( 1, 'Name is required' ),
startDate: z.coerce.date(),
endDate: z.coerce.date()
} ).refine(
data => data.startDate < data.endDate,
{
message: 'End date must be after start date',
path: [ 'endDate' ],
}
)
const result = schema.safeParse( {
name: 'John',
startDate: '2023-02-21',
endDate: '2023-02-20',
something: { key: 'value' }
} )
!result.success && console.log( result.error.issues )
// [
// {
// code: 'custom',
// message: 'End date must be after start date',
// path: [ 'endDate' ]
// }
// ] Can you explain specifically what you mean by 'not work'? |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
duynd243
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Everything seems to be working as expected for me.