乐闻世界logo
搜索文章和话题

How can zod date type accept ISO date strings?

1个答案

1

When using the zod library for data validation, you can use zod.date() to create a date validator.

To accept and validate an ISO date string, you need to use zod.string() to ensure the input is a string and combine it with zod.preprocess() to convert the string into a Date object.

This allows you to first validate that the string conforms to the ISO format and then convert it into a JavaScript Date object.

The implementation steps are as follows:

  1. Use zod.string() to ensure the input is a string.

  2. Use zod.preprocess() to convert valid ISO strings into Date objects.

  3. Use zod.date() to ensure the converted result is a valid Date object.

Here is a specific example code:

javascript
import { z, ZodError } from 'zod'; const isoDateStringSchema = z.preprocess((arg) => { if (typeof arg === 'string') { const date = new Date(arg); if (!isNaN(date.getTime())) { return date; } } return arg; }, z.date()); try { // Test a valid ISO date string const result = isoDateStringSchema.parse('2021-12-01T14:48:00.000Z'); console.log(result); // Correct output: 2021-12-01T14:48:00.000Z (Date object) } catch (e) { if (e instanceof ZodError) { console.log(e.errors); // If there's an error, print error information } } try { // Test an invalid ISO date string isoDateStringSchema.parse('not-a-date'); } catch (e) { if (e instanceof ZodError) { console.log(e.errors); // Correctly captures errors and prints them } }

In this example, the preprocess function attempts to convert the input string into a Date object. If the conversion is successful and the result is a valid date (i.e., the Date object is not 'Invalid Date'), the preprocessing function returns the Date object. Then, z.date() validates that the object is indeed a valid Date object.

This approach allows you to flexibly handle and validate ISO date strings, ensuring they are correctly used as Date objects in your application.

2024年7月21日 19:46 回复

你的答案