zod icon indicating copy to clipboard operation
zod copied to clipboard

Datetime validation without offset should allow omission of Z zone designator

Open MattSidor opened this issue 2 years ago • 6 comments

ISO-8601 allows datetime strings to not have any timezone offset or Z zone designator. In these instances, it is assumed to be in local time. (Reference: https://en.wikipedia.org/wiki/ISO_8601#Local_time_(unqualified))

However, the datetime validator currently marks these as invalid.

const schema = z.string().datetime() // offset: false is default behavior
console.log( schema.safeParse( '2022-01-01T00:00:00' ).success ) // false

MattSidor avatar Apr 28 '23 17:04 MattSidor

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 27 '23 19:07 stale[bot]

This is still an issue. I am still working on the draft PR for it.

bchrobot avatar Jul 30 '23 11:07 bchrobot

I've opened PR that adds optional support for local (unqualified) date times here #2913

0xturner avatar Oct 28 '23 04:10 0xturner

My workaround is just to refine for now. This also makes seconds optional.

const Timestamp = z
  .string()
  .refine(
    (value) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(value),
    {
      message:
        "timestamp must be of the unqualified form yyyy-mm-ddThh:mm[:ss[.mmm]]",
    },
  );

Example on where unqualified timestamps can come from using upcoming TC39 Temporal

> Temporal.Now.plainDateTimeISO('UTC').toString()
'2023-11-25T03:56:32.870588264'
> Temporal.Now.plainDateTimeISO('UTC').toString({smallestUnit: 'minute'})
'2023-11-25T03:56'

Pyrolistical avatar Nov 25 '23 03:11 Pyrolistical

This is an issue as well for us, dealing with OpenAPI datetime fields.

We are using zod-to-openapi to build clients for services we use - it sees an OpenAPI schema like "type": "string", "format": "date-time" and turns it into z.string().datetime({ offset: true }) - which is technically correct.

But we have an API that actually returns a datetime with no trailing Z - so when we query it, the zodios API throws a validation error as it's not a valid ISO8601 (well, really rfc3339) datetime.

The root problem is that API - but having a workaround in Zod would be very useful.

kornysietsma avatar Feb 22 '24 17:02 kornysietsma

Just encountered this same issue

Armadillidiid avatar Mar 05 '24 16:03 Armadillidiid

This is almost a year old. Please prioritize this Zod team. I'm here because Zod validation is failing on dates coming from our ERP system. edit: we decided to just use a preprocess to fix the date, which isn't great...

jcollum-nutrien avatar Apr 11 '24 23:04 jcollum-nutrien

This is available in canary and will land in Zod 3.23.

colinhacks avatar Apr 12 '24 03:04 colinhacks