Home > Software engineering >  How can zod date type accept ISO date strings?
How can zod date type accept ISO date strings?

Time:01-18

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

CodePudding user response:

You have to expect a string instead

const someTypeSchema = z.object({
    t: z.string().refine((arg) =>
      arg.match(
        /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)((-(\d{2}):(\d{2})|Z)?)$/
    ))
})

CodePudding user response:

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)
    const parsed = JSON.parse(stringified)
    const validated = someTypeSchema.parse(parsed) // <- Throws error! "Expected date, received string"
    console.log(validated.t)
}
main()
  • Related