DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #9

Complex Schema Validation

Our Form has name, email, and optionally will have phoneNumber and website.

const Form = z.object({
  name: z.string(),
  phoneNumber: z.string().optional(),
  email: z.string(),
  website: z.string().optional(),
});

export const validateFormInput = (values: unknown) => {
  const parsedData = Form.parse(values);

  return parsedData;
};
Enter fullscreen mode Exit fullscreen mode

We want to put some constraints on what the values can be.

The user should not be able to pass an invalid URL, phone numbers, or website URLs.

We will find Zod APIs for adding validation to our Form types.

👉 Solution:

The strings section of the Zod docs includes several examples of validation helpers that can be used to validate our Form types.

Here is what the Form schema looks like now:

const Form = z.object({
  name: z.string().min(1),
  phoneNumber: z.string().min(5).max(20).optional(),
  email: z.string().email(),
  website: z.string().url().optional(),
});
Enter fullscreen mode Exit fullscreen mode

name has min(1) added because we can not pass in an empty string.

phoneNumber are constrained with min(5) and max(20) while still being optional.

Zod also has built-in validators for email and url, saving us from writing our own.

Note that we can not use .optional().min() because min does not exist on the optional types. This means we have to put .optional() at the end after other validations.

There are additional validation resources linked in the Zod docs.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)