Search code examples
node.jstypescriptdatezod

How can zod date type accept ISO date strings?


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()

Solution

  • Discovered that I can accept a string for the property, and use transform to turn it into a Date during parsing

    import { z } from "zod"
    
    const someTypeSchema = z.object({
        t: z.string().transform((str) => new Date(str)),
    })
    type SomeType = z.infer<typeof someTypeSchema>
    
    function main() {
        const obj1: SomeType = {
            t: new Date(),
        }
        const stringified = JSON.stringify(obj1)
        console.log(stringified) // <-- {"t":"2023-09-07T07:19:51.128Z"}
        const parsed = JSON.parse(stringified)
        const validated = someTypeSchema.parse(parsed)
        console.log(validated.t instanceof Date) // <-- "true"
    }
    main()