Zod's Validation: Unleashing Precision in Data Handling

Zod's Validation: Unleashing Precision in Data Handling

Elevate Your Data Integrity with Zod's Seamless Validation Process

What is Zod?

Zod is a TypeScript go-to for declaring and validating schemas! Think of Zod as your helpful sidekick, navigating you through different data types, from plain strings to intricate nested objects.

Advantages of using Zod

  1. Zod stands out as a robust validation library, delivering power and ease of use for TypeScript and JavaScript applications.

  2. With its straightforward and expressive syntax, Zod simplifies the process of defining complex validation schemas.

  3. Zod's compatibility with well-known frameworks, including Express, ensures seamless integration, making it a versatile choice for diverse development scenarios.

Installation

You can install Zod by using any of these methods

npm install zod   # NPM
yarn install zod # Yarn
bun add zod    # BUN
pnpm add zod # PNPM

Usage

Validating Form Input and Response

import { AxiosError } from 'axios';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import Axios from '@/lib/Axios';

const FormSchema = z.object({
  email: z.string().email().trim().toLowerCase(),
  password: z.string(),
});

const ResponseSchema = z.object({
  token: z.string(),
  data: z.object({
    user: z.object({
      _id: z.string(),
      first_name: z.string(),
      last_name: z.string(),
      email: z.string(),
      phone_number: z.string(),
      role: z.array(z.string()),
    }),
  }),
});

type ResponseSchemaType = z.infer<typeof ResponseSchema>;

Using useForm to connect the form

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  });
  async function onSubmit(values: z.infer<typeof FormSchema>) {

    try {
      const { data, status } = await Axios.post<ResponseSchemaType>('/users/login', values);
       ...
    } catch (error) {
      if (error instanceof AxiosError) {
       ...
      }
    }
  }

Using it with ShadCN UI form

 <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="my-5 space-y-4">
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Email</FormLabel>
                <FormControl>
                  <Input placeholder="Enter Email" className="h-12 border" {...field} />
                </FormControl>
                <FormDescription />
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Password</FormLabel>
                <FormControl>
                  <div className="relative">
                    <Input
                      type={showPassword ? 'text' : 'password'}
                      placeholder="Enter Password"
                      className="h-12 border"
                      {...field}
                    />
                    <span className="absolute right-4 top-3 cursor-pointer  ">
                      {showPassword ? (
                        <EyeOffIcon onClick={toggleShow} size={22} className={iconStyle} />
                      ) : (
                        <EyeIcon onClick={toggleShow} size={22} className={iconStyle} />
                      )}
                    </span>
                    <div className="w-full flex justify-end">
                      <Link href={'/forgot-password'} className="text-right my-2 text-primary-500">
                        {content.forgotPassword.text}
                      </Link>
                    </div>
                  </div>
                </FormControl>
                <FormDescription />
                <FormMessage />
              </FormItem>
            )}
          />

            <Button size="2xl" className="w-full " disabled={form.isSubmitting}>
              <span className="font-bold text-center text-base leading-[20px]">Login</span>
            </Button>
        </form>
      </Form>

Conclusion

I trust you'll find this information beneficial. For a more in-depth exploration of usage and existing features, feel free to visit the Zod website. There, you can discover a wealth of insights and details to further enhance your understanding. Happy exploring!