Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate HTML input date tag using zod with React

Tags:

zod

reactjs

Currently I have a React-application with a useState object. As the user enters a date into an <input type="date" />, it stores that value to the useState object.

I am trying to validate the input afterwards with Zod. But it fails since the input is stored as a string, and I am trying to validate the input as a date (z.date()).

Now, do I have to, if it's possible, convert the input from a string to a date? Or is it fine storing the date as a string and just change the validation to accept a string?

I guess it depends on how the database is supposed to work. Any tips/recommendations/thoughts on this? What would be your approach and what's the alternatives?

like image 526
Fredrik Johansson Avatar asked Oct 23 '25 17:10

Fredrik Johansson


1 Answers

I think the core of your question is asking how to use zod to parse a Date from a string, which the zod docs actually have an example for how to do in the Dates section.

const dateSchema = z.preprocess((arg) => {
  if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());

Here they create a dateSchema that preprocesses the input to attempt to convert string inputs into Date objects before handing them into the date core schema.

If you have further restrictions, you can apply those to the z.date() call. (For example you could set a minimum or maximum date).

like image 136
Souperman Avatar answered Oct 26 '25 08:10

Souperman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!