Skip to content

Refine for object when using zod not work without optional #2071

Answered by JacobWeisenburger
duynd243 asked this question in Q&A
Discussion options

You must be logged in to vote

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',
//       …

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@duynd243
Comment options

@JacobWeisenburger
Comment options

@manhhung-fpt
Comment options

Answer selected by duynd243
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants