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'
})
)
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 - drizzle-zod
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
1 Reply
Chev
ChevOP3w ago
Solved with the following:
export const newTestSchema = createInsertSchema(Test, {
startedAt: z.date(),
completedAt: z.date().optional()
})
.omit({
id: true,
})
.refine(
({ startedAt, completedAt }) => {
const now = new Date()
if (startedAt > now) return false

if (completedAt == null) return true

return completedAt <= now && completedAt > startedAt
},
() => ({
path: ['startedAt', 'completedAt'],
message: 'completed date at must be after started date'
})
)
export const newTestSchema = createInsertSchema(Test, {
startedAt: z.date(),
completedAt: z.date().optional()
})
.omit({
id: true,
})
.refine(
({ startedAt, completedAt }) => {
const now = new Date()
if (startedAt > now) return false

if (completedAt == null) return true

return completedAt <= now && completedAt > startedAt
},
() => ({
path: ['startedAt', 'completedAt'],
message: 'completed date at must be after started date'
})
)

Did you find this page helpful?