DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Dynamically Modifying Validation Schemas in Zod: A TypeScript and React-Hook-Form Example

Table of Contents

  1. Introduction
  2. What is Zod?
  3. Creating Dynamic Schemas: User Registration and User Information Editing
  4. Conclusion

Introduction

When handling form validation in React applications, it's common to use Zod in conjunction with React Hook Form. However, what should you do when the same form is used in different scenes and certain fields are required or optional based on these conditions? In this article, we will introduce how to create dynamic validation schemas in Zod.

What is Zod?

Zod is a runtime validation library for TypeScript. Zod provides powerful schema definition capabilities for validating all types of data. Additionally, these schemas can be used as TypeScript types, allowing you to write type-safe code.

Creating Dynamic Schemas: User Registration and User Information Editing

Let's consider a specific situation. We have a user registration screen and a user information editing screen, each with a form. These two screens use almost the same form, but there is one difference. On the user registration screen, the "Agree to Terms and Conditions" checkbox is required, but on the user information editing screen, this field does not exist.

In such cases, we create a function to dynamically generate a schema based on the isEdit parameter. Here is the relevant code:

import * as z from 'zod';

export const createProfileSchema = (isEdit: boolean) => {
    let isAgreeTermsSchema = isEdit ? z.boolean().optional() : z.boolean();

    return z
        .object({
            // Other fields go here...
            isAgreeTerms: isAgreeTermsSchema,
        });
};
Enter fullscreen mode Exit fullscreen mode

We generate the schema using this function:

const {
    params: { isEdit }
} = useRoute<ProfileEntryRouteProp>();

const profileSchema = createProfileSchema(isEdit);
Enter fullscreen mode Exit fullscreen mode

This way, when isEdit is false (on the user registration screen), isAgreeTerms is a required field, and when isEdit is true (on the user information editing screen), isAgreeTerms does not exist (is optional).

Conclusion

In this article, we introduced how to create dynamic validation schemas in Zod. By using this method, you can dynamically change whether a field is required or optional based on specific conditions. This makes the combination of Zod and React Hook Form an even more powerful tool.


That's all for this article. I hope it was helpful to you. If you have any questions, please let me know in the comments. Also, don't forget to like this article if you found it useful!

Top comments (2)

Collapse
 
tiredpyrx profile image
tiredpyrx

showing ternary operation as "dynamic" schema

Collapse
 
bekzodjonganiyev profile image
bekzodjonganiyev

Thank you bro, this is very usefull content for me