Parsing a date #879
-
Very surprised that I could not find anything on this. If I have a date schema Am I supposed to use a transform here? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 8 replies
-
There are a few ways to handle what you are trying to do: const dateSchema = z.preprocess( arg => typeof arg == 'string' ? new Date( arg ) : undefined, z.date() )
dateSchema.safeParse( '2022-01-12T00:00:00.000Z' ) // success: true
dateSchema.safeParse( new Date( '2022-01-12T00:00:00.000Z' ) ) // success: false const stringToDate = z.string().transform( arg => new Date( arg ) )
stringToDate.safeParse( '2022-01-12T00:00:00.000Z' ) // success: true
dateSchema.safeParse( new Date( '2022-01-12T00:00:00.000Z' ) ) // success: false const stringOrDateToDate = z.string().or( z.date() ).transform( arg => new Date( arg ) )
stringOrDateToDate.safeParse( '2022-01-12T00:00:00.000Z' ) // success: true
stringOrDateToDate.safeParse( new Date( '2022-01-12T00:00:00.000Z' ) ) // success: true Hope this helps. Let me know if you have any questions. I also added a pull request to add documentation about z.date. Sorry for the confusion cause by not having any documentation. 2022-02-11 update: |
Beta Was this translation helpful? Give feedback.
-
I ran into this today and thought I would add my solution to this discussion in case others come by: const stringToValidDate = z.string().transform((dateString, ctx) => {
const date = new Date(dateString);
if (!z.date().safeParse(date).success) {
ctx.addIssue({
code: z.ZodIssueCode.invalid_date,
})
}
return date;
}) I did not want to use This transform covers all the cases I need covered. Zod expects a string value in (as I am getting ISO strings from an external API) and will output a Date object only if the string is parsable into a valid date. |
Beta Was this translation helpful? Give feedback.
-
Since v3.20, this got way easier. Let me know if this works for you? Code updated on 2023-02-25. Thanks to @pilotmoon, for the idea. const stringToDate = z.string().pipe( z.coerce.date() )
console.log( stringToDate.safeParse( '2023-01-10' ).success ) // true
console.log( stringToDate.safeParse( '2023-13-10' ).success ) // false
console.log( stringToDate.safeParse( null ).success ) // false the |
Beta Was this translation helpful? Give feedback.
-
According to the readme as it stands today, you can now do: const dateValidatorAcceptsString = z.coerce.date(); I don't see any information about |
Beta Was this translation helpful? Give feedback.
-
@JacobWeisenburger this seems to be a good solution for my usecase of validating that dates are date-like. I'm trying to generate types from Zod objects that make use of this via Eg:
|
Beta Was this translation helpful? Give feedback.
Since v3.20, this got way easier.
Let me know if this works for you?
Code updated on 2023-02-25. Thanks to @pilotmoon, for the idea.
the
dates
section has been updated in the READMEhttps://github.com/colinhacks/zod#dates