Onurhan Demir

Using Zod to validate date range picker

·5 min

What is Zod?

Prerequisites

I used shadcn/ui for the date range picker component, date-fns for the date format, and zod for the validation.

Getting started

Creating challenges on the Lotus project requires attention to detail, especially when setting the start and end dates. To simplify this process for others, I wrote a blog about creating a date range selection component for the challenge creation form.

First, I use Zod to create a new schema called dateRangeSchema. This schema has a date range object with the start date and end date of the form data.

Now that the Zod schema is ready, I will create the form step by step, starting with the necessary imports.

Schema and imports are done. Now I can create the component. When I create the component, I first define defaultValues and resolver using useForm.

  • defaultValues is a property that sets the initial values of the form fields when the form is first loaded or reset.
  • zodResolver is a function that converts a Zod schema into a form resolver, ensuring that the form data matches the schema before submission.

Now everything is ready. Finally, I include the date range picker in Component using shadcn/ui forms.

Now we have everything ready. To make the code better,

  • You can make Date Range Picker a component.
  • You can improve the onSubmit functionality of the form by using the Sonner package.
  • You can add custom error messages to the schema.

follow me on X.