refine and createInsertSchema

createInsertSchema accepts and option to further refine the schema

I would like to validate fields against each other like ensuring a completedAt field is date after a startedAt field.

export const Test = pgTable('test', {
  startedAt: timestamp(timezoneConfig).defaultNow().notNull(),
  completedAt: timestamp(timezoneConfig),
})

    const schema = z
      .object({
        startedAt: z.date().max(new Date()),
        completedAt: z.date().max(new Date()).optional()
      })
      .refine(
        ({ startedAt, completedAt }) => {
          if (completedAt == null) return true

          return completedAt > startedAt
        },
        () => ({
          path: ['startedAt', 'completedAt'],
          message: 'completed date at must be after started date'
        })
      )
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
Was this page helpful?