DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

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:

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay