When defining a schema with zod, how do I use a date type?
If I use z.date()
(see below) the date object is serialized to a ISO date string. But then if I try to parse it back with zod, the validator fails because a string is not a date.
import { z } from "zod"
const someTypeSchema = z.object({
t: z.date(),
})
type SomeType = z.infer<typeof someTypeSchema>
function main() {
const obj1: SomeType = {
t: new Date(),
}
const stringified = JSON.stringify(obj1)
console.log(stringified)
const parsed = JSON.parse(stringified)
const validated = someTypeSchema.parse(parsed) // <- Throws error! "Expected date, received string"
console.log(validated.t)
}
main()
I used this from the README which works since v3.20 https://github.com/colinhacks/zod#dates
In your code snippet it would turn into this:
import { z } from "zod"
const someTypeSchema = z.object({
t: z.coerce.date(),
})
type SomeType = z.infer<typeof someTypeSchema>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With