Search code examples
reactjszod

Validate HTML input date tag using zod with React


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?


Solution

  • 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).