Search code examples
react-hook-formzod

How to get sub-schema from zod object schema


I have a schema like this:

const schema = z.object({
  name: z.string(),
  email: z.string()
})

Later in the code, I want to validate just email. Is it possible to get somehow email schema like this: schema.getSubschema("email").safeParse(...)? I know I can separately define schema for an email but I would be more convienient to get it from the object schema.

EDIT

const saveHomeworkSchema = z
  .object({
    description: description,
    solution: description,
    video: file.optional(),
    images: files.optional(),
    domain: selectItem,
    theorems: theorems,
    definitions: definitions,
    tags: tags,
    isFree: z.any(),
    price: price,
    status: z.nativeEnum(HomeworkStatus),
  })
  .refine(
    (data) => data.solution || data.video || data.images?.length,
    'Musisz podać przynajmniej jeden format rozwiązania.'
  );


Solution

  • You can use .shape in this case:

    const schema = z.object({
      name: z.string(),
      email: z.string()
    });
    let email = '[email protected]';
    
    console.log(schema.shape.email.safeParse(email))
    

    You can learn more here