Zod date string validation

Someone that knows how I can use datetime string validation in zod but only require the year month and day and not the time?
const datetime = z.string().datetime();

datetime.parse("2020-01-01T00:00:00Z"); // pass
datetime.parse("2020-01-01") // fail but I want this to work

// This is how my validation looks like right now for this field in my schema
bought: z.string().datetime(tValidation('DATE.MUST_BE_DATE')),
const datetime = z.string().datetime();

datetime.parse("2020-01-01T00:00:00Z"); // pass
datetime.parse("2020-01-01") // fail but I want this to work

// This is how my validation looks like right now for this field in my schema
bought: z.string().datetime(tValidation('DATE.MUST_BE_DATE')),
Do I need to write my own regex validation for it instead?
8 Replies
Neto
Neto2y ago
using z.coerce.date() can fix that no ?
// c.l = console.log

c.l(dateSchema.safeParse('2023-01-10T00:00:00.000Z').success) // true
c.l(dateSchema.safeParse('2023-01-10').success) // true
// c.l = console.log

c.l(dateSchema.safeParse('2023-01-10T00:00:00.000Z').success) // true
c.l(dateSchema.safeParse('2023-01-10').success) // true
Wezter
Wezter2y ago
okey and it would then fail if I sent in something that isn't a substring of datetime?
Neto
Neto2y ago
as long as the value works with new Date(value) it will pass after the value is valid you can correct_value.toISOString() if you want
Wezter
Wezter2y ago
How should it then look in my schema? This is how it currently looks
const schema = z.object({
bought: z.string().datetime(tValidation('DATE.MUST_BE_DATE')),
});
const schema = z.object({
bought: z.string().datetime(tValidation('DATE.MUST_BE_DATE')),
});
Neto
Neto2y ago
bought: z.coerce.date({...}) If you want the string version of the date, then you can parse later
Wezter
Wezter2y ago
Maybe it would be cleaner to just add regex for it instead? Something like this? const isIsoDate = /\d{4}-[01]\d-[0-3]\d/;
Neto
Neto2y ago
i mean if you want to
Wezter
Wezter2y ago
then I don't have to both parse and coerce it
Want results from more Discord servers?
Add your server