Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ How to Validate a Date Range Picker with Zod in TypeScript Projects

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š How to Validate a Date Range Picker with Zod in TypeScript Projects


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

What is Zod?

Zod is a TypeScript-first schema declaration and validation library.

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 an 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.

import { z } from "zod";
export const dateRangeSchema = z
  .object({
    // other fields
    dateRange: z.object(
      {
        from: z.date(),
        to: z.date(),
      },
      {
        required_error: "Please select a date range",
      }
    ),
  })
  .refine((data) => data.dateRange.from < data.dateRange.to, {
    path: ["dateRange"],
    message: "From date must be before to date",
  });

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

I have added the dateRangeSchema content to @/zod/schemas/date-range.ts. You can save it in the file if you want but don't forget to edit it if necessary.

import { cn } from "@/lib/utils";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { format } from "date-fns";
import { CalendarIcon } from "lucide-react";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "../ui/form";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { dateRangeSchema } from "@/zod/schemas/date-range";

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.
export const Component = () => {
  const form = useForm({
    defaultValues: {
      dateRange: {
        from: new Date(),
        to: new Date(),
      },
    },
    resolver: zodResolver(dateRangeSchema),
  });

  const onSubmit = (data: z.infer<typeof dateRangeSchema>) => {
    console.log(data);
  };

  return (
    // ...
  );
};

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

return (
  <Form {...form}>
    <form onSubmit={form.handleSubmit(onSubmit)}>
      <FormField
        control={form.control}
        name="dateRange"
        render={({ field }) => (
          <FormItem className="flex flex-col">
            <FormLabel>Start and End Date</FormLabel>
            <Popover modal={true}>
              <PopoverTrigger asChild>
                <Button
                  id="date"
                  variant="outline"
                  className={cn(
                    "w-full justify-start text-left font-normal",
                    !field.value.from && "text-muted-foreground"
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {field.value.from ? (
                    field.value.to ? (
                      <>
                        {format(field.value.from, "LLL dd, y")} -{" "}
                        {format(field.value.to, "LLL dd, y")}
                      </>
                    ) : (
                      format(field.value.from, "LLL dd, y")
                    )
                  ) : (
                    <span>Pick a date</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="center">
                <Calendar
                  initialFocus
                  mode="range"
                  defaultMonth={field.value.from}
                  selected={{
                    from: field.value.from!,
                    to: field.value.to,
                  }}
                  onSelect={field.onChange}
                  numberOfMonths={2}
                />
              </PopoverContent>
            </Popover>
            <FormDescription>Select the start and end date</FormDescription>
            <FormMessage />
          </FormItem>
        )}
      />
    </form>
  </Form>
);

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.

...



๐Ÿ“Œ How to Validate a Date Range Picker with Zod in TypeScript Projects


๐Ÿ“ˆ 105.46 Punkte

๐Ÿ“Œ Exploring Zod and the Benefits of Schema-Based Validation in TypeScript Projects


๐Ÿ“ˆ 46.82 Punkte

๐Ÿ“Œ Zod - Validate your API inputs with ease


๐Ÿ“ˆ 42.79 Punkte

๐Ÿ“Œ How to Validate Forms with Zod and React-Hook-Form


๐Ÿ“ˆ 42.79 Punkte

๐Ÿ“Œ Medium CVE-2021-40892: Validate color project Validate color


๐Ÿ“ˆ 36.63 Punkte

๐Ÿ“Œ Zod: The Next Biggest thing after Typescript


๐Ÿ“ˆ 36.39 Punkte

๐Ÿ“Œ Zod 101 - A Typescript-first Schema Validation Library


๐Ÿ“ˆ 36.39 Punkte

๐Ÿ“Œ Master schema validation in TypeScript with Zod


๐Ÿ“ˆ 36.39 Punkte

๐Ÿ“Œ Creating Dynamic Forms with React, Typescript, React Hook Form and Zod


๐Ÿ“ˆ 36.39 Punkte

๐Ÿ“Œ System Color Picker 1.15.0 - The built-in color picker.


๐Ÿ“ˆ 35.53 Punkte

๐Ÿ“Œ Horizontal Calendar - a simple date picker for React Native


๐Ÿ“ˆ 28.13 Punkte

๐Ÿ“Œ How to Add Custom Buttons to a Date Picker in Flatpickr


๐Ÿ“ˆ 28.13 Punkte

๐Ÿ“Œ Quick Tip: Creating a Date Picker in React


๐Ÿ“ˆ 28.13 Punkte

๐Ÿ“Œ React and express.js form validations with Zod


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ This Week In React #128: SWR, Vite, Codux, Storybook, Next.js, Forget, Nylon, Paper, align-deps, INP, Zod, Tauri...


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ This Week In React #130: Next.js, callback ref, Zod, Redux, React-Hook-Form, Redux, mdxjs-rs, Tamagui, Skia, Shopify, Solid...


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Zod Crash Course


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Learn "Zod" In 5 Minutes


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Validating forms in React Apps with Zod


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Effortlessly Generate Structured Information with Ollama, Zod, and ModelFusion


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Translating zod errors with next-intl


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ React 19, handling forms using useOptimistic and useFormStatus along with React Hook Form and Zod โ€ฆ practical example


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ From Flaky to Flawless: Angular API Response Management with Zod


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Simplifying Form Validation with Zod and React Hook Form


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Zod: Zero to Hero - Chapter 1


๐Ÿ“ˆ 24.47 Punkte

๐Ÿ“Œ Range Rover SV Autobiography Dynamic: So fรคhrt sich der stรคrkste Range aller ...


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ Range Rover Velar: BMW X4 aus England: Range Rover Velar im ersten Check


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ New Long-Range Wi-Fi Standard Offers Double Range to Home Devices


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ New Long-Range Wi-Fi Standard Offers Double Range to Home Devices


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ Fahrbericht Range Rover Velar P380: Erste Serie schon ausverkauft: Range ...


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ Tesla Unveils 500-Mile Range Semi Truck, 620-Mile Range Roadster 2.0


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ Range Rover Sport EV: Elektrischer Range Rover kommt in diesem Jahr


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ Tesla Cuts Price of Model S Long Range Plus, Says EPA-Rated Range Improved To 402 Miles


๐Ÿ“ˆ 24.39 Punkte

๐Ÿ“Œ 10 typescript developers you must follow to become typescript expert in 2024


๐Ÿ“ˆ 23.84 Punkte

๐Ÿ“Œ I made "TypeScript Swagger Editor", new type of Swagger UI writing TypeScript code in the browser


๐Ÿ“ˆ 23.84 Punkte











matomo