Generate a dynamic zod schema for a user created form

If a user is creating a form we output this:

{
    "sections": [
        {
            "id": "8fa76f1e-4ba8-4077-9265-e10f4c5f2be8",
            "title": "Example Title",
            "fields": [
                {
                    "id": "85354302-d313-4c28-93d9-acfa2ef4b2aa",
                    "type": "textfield",
                    "title": "First Name",
                    "default": true,
                    "private": false,
                    "required": true,
                    "response": "",
                },
                {
                    "id": "51921ab2-8fe4-40ef-a2ec-140c6658533a",
                    "type": "textfield",
                    "title": "Last Name",
                    "default": true,
                    "private": false,
                    "required": true,
                    "response": "",
                },
                {
                    "id": "6e274a04-d63f-4913-8b3b-0a0d66aa59bf",
                    "type": "email",
                    "title": "Email Address",
                    "default": true,
                    "private": false,
                    "required": true,
                    "response": "",
                },
                {
                    "id": "78e25934-abe7-4404-b863-f0358329982f",
                    "type": "textfield",
                    "title": "Short Text",
                    "default": false,
                    "private": false,
                    "required": false,
                    "response": "",
                }
            ],
        }
    ]
}


how do i generate a schema to use in the react-hook-form zod resolver to validate the fields? notice how we have sections->fields, and each field has a "required" which indicates true/false, and then "response" is where we capture the response. we generate a different field object to represent required/optional based on the "type" of the field, e.g. "textfield" is a basic zod object string

i've tried several things
Was this page helpful?