Zod array of dates

Can someone help me validate that a variable is an array of exactly two dates and ideally in the future. Here is what I've currently got. However it allows an array of two nulls which isn't what I want.
date: z.array(z.date(), {
required_error: "Departure & Return Date is required",
invalid_type_error: "Departure & Return Date is required",
}),
date: z.array(z.date(), {
required_error: "Departure & Return Date is required",
invalid_type_error: "Departure & Return Date is required",
}),
7 Replies
deforestor
deforestor2y ago
So, it should be an array of exactly 2 dates? If so, you can achieve it like this:
dates: z.array(z.date()).length(2),
dates: z.array(z.date()).length(2),
Smadger
SmadgerOP2y ago
For some reason this doesn't flag when date is an array of two nulls.
deforestor
deforestor2y ago
Well that is very interesting and almost sounds like a bug.. You could workaround it by using the .refine
deforestor
deforestor2y ago
GitHub
GitHub - colinhacks/zod: TypeScript-first schema validation with st...
TypeScript-first schema validation with static type inference - GitHub - colinhacks/zod: TypeScript-first schema validation with static type inference
deforestor
deforestor2y ago
Also, I'm not 100% sure that's how you want it, but you could try something like this:
dates: z.array(z.date().refine(d=>
d!= null
// is in the future
&& (d > new Date())
)).length(2),
dates: z.array(z.date().refine(d=>
d!= null
// is in the future
&& (d > new Date())
)).length(2),
Smadger
SmadgerOP2y ago
Cheers
deforestor
deforestor2y ago
let me know if it works
Want results from more Discord servers?
Add your server