Zod Typesafe User Input

What is Zod?

Zod is a TypeScript-first schema declaration and validation library. It ensures that your data is valid before it is submitted to the server, which means less invalid data and fewer errors on your end. Additionally, Zod allows you to create custom input types to tailor the user experience to your specific needs. Overall, using Zod can help streamline your development process by making sure that your forms, inputs, and API requests are error-free from the start. If you're looking for a reliable way to create typesafe forms and inputs, Zod is worth checking out!

How can Zod help with type safety in forms and input from users?

Zod can help ensure that your forms and input are type-safe, so you won't accidentally allow incorrect data types to be entered into your system. This can help prevent errors from happening in the first place and means that you don't have to write custom validation code for your forms and input fields.

Zod can also help enforce rules around what data can be entered into your forms and input fields, ensuring that only valid data is accepted. By using Zod, you can avoid having to write any extra code or manually check user input against these rules - it will all be handled automatically by Zod. This makes your forms and inputs more reliable and robust against errors.

Overall, using Zod can help improve the quality of your forms and input, making them easier to use, more accurate, and less prone to error.

Why should developers consider using Zod?

Zod offers type-checking for JavaScript, which can be helpful for developers who want to ensure their code is error-free. Zod's validation methods can also be used to enforce input from users, ensuring that only valid data is submitted. Using Zod can help make your development process more efficient and reduce the risk of introducing bugs into your codebase.

How to get started with Zod

First, you need to make sure you have strict mode enabled in your Typescript project.

Then install the Zod package.

npm install zod 
yarn add zod
pnpm add zod

Simple schemas

Now you can create a schema to handle your needs, lets's say we want all inputs to be a string we can do that:

import { z } from "zod";

// my schema should be a string

const mySchema = z.string();

mySchema.parse("Zod is awesome"); 
mySchema.parse(69) // throws an error because it is not a string
jsx

Now in some cases, we don't want to throw an error we want Zod to tell us we have had an invalid input so we can handle it somewhere else in the stack

import { z } from "zod";


const mySchema = z.string();

mySchema.safeParse("Zod is still really cool");
// This will return { success: true: data: "Zod is still really cool"}


mySchema.safeParse(69)
// This will return { success: false: error: ZodError }
jsx

Object schemas

Object schemas allow you to handle complex inputs and validate them and give you an inferred type.

import { z } from "zod";

const User = z.object({
  name: z.string(),
  username: z.string(),
  age: z.number(),
  email: z.string()
});

User.parse({ name: "James Perkins", username: "jamesperkins", age: 33, email: "contactme@jamesperkins.dev" });

// extract the inferred type
type User = z.infer<typeof User>;
// {name: string, username: string, age: number, email: string }
jsx

Built-in string validation

One part no one wants to write is the regex to validate strings, I wrote a regex package a few years ago because who wants to remember how to validate the user input of an email? Zod provides a handful of validators, lets's improve our User object:

import { z } from "zod";

const User = z.object({
  name: z.string(),
  username: z.string().min(5),
  age: z.number(),
  email: z.string().email()
});

User.parse({ name: "James Perkins", username: "jamesperkins", age: 33, email: "contactme@jamesperkins.dev" });

// extract the inferred type
type User = z.infer<typeof User>;
// {name: string, username: string, age: number, email: string }
jsx

Now a user has to input an email in our email field, which will be validated, and our username must be at least five characters.

Custom error messages

Zod allows you to provide a custom error to present to the user so they understand why they need to change input.

import { z } from "zod";

const User = z.object({
  name: z.string(),
  username: z.string().min(5, {message: "The username must be at least 5 characters"),
  age: z.number(),
  email: z.string().email({message: "The inputted email is invalid, please enter a valid email")
});

User.parse({ name: "James Perkins", username: "jamesperkins", age: 33, email: "contactme@jamesperkins.dev" });

// extract the inferred type
type User = z.infer<typeof User>;
// {name: string, username: string, age: number, email: string }
jsx

This is just the beginning of Zod, if you are interested, you can check out their documentation.