If you want to validate an array of objects from this Schema

const fieldsOfEng = [
  {
    id: "ELECTRICAL",
    name: "Electrical",
    experience: 1,
  },
  {
    id: "MECHANICAL",
    name: "Mechanical",
    experience: undefined,
  },
];

I'd do it like this

const userInfoSchema = z.object({
  id: z.string(),
  name: z.string(),
  experience: z.number().optional()
})

// Now add this object into an array
const usersInfoSchema = z.array(userInfoSchema)
Answer from Ark on Stack Overflow
Top answer
1 of 3
43

If you want to validate an array of objects from this Schema

const fieldsOfEng = [
  {
    id: "ELECTRICAL",
    name: "Electrical",
    experience: 1,
  },
  {
    id: "MECHANICAL",
    name: "Mechanical",
    experience: undefined,
  },
];

I'd do it like this

const userInfoSchema = z.object({
  id: z.string(),
  name: z.string(),
  experience: z.number().optional()
})

// Now add this object into an array
const usersInfoSchema = z.array(userInfoSchema)
2 of 3
8

This answer is an update on my progress so far. I closer to getting my schema validation working correctly but for some reason it is not submitting. I could solve this faster if I could get react-hook form's errors to output correctly but since I'm using template literals when I'm registering the inputs, the error is just outputting nothing. I DO know there is an error though because my truthy error outputs the "professions:" string that I added in the p-tag.

Data for checkboxes in form (this is the data I'm validating via zod):

const fieldsOfEng = [
  {
    id: "ELECTRICAL",
    name: "Electrical",
    experience: undefined,
  },
  {
    id: "MECHANICAL",
    name: "Mechanical",
    experience: undefined,
  },

Schema for validation: I'm checking that the name they select is included in my fieldsOfEng array and making sure the experience is greater than 1.

const userInfoSchema = object({
professions: z
    .object({
      name: z
        .string()
        .refine((name) =>
          fieldsOfEng.map((field) => field.name).includes(name)
        ),
      experience: z.number().refine((experience) => experience > 1),
    })
    .array(),
});

React hook form:

type userInfoType = z.infer<typeof userInfoSchema>;

  const {
    register,
    watch,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<userInfoType>({
    resolver: zodResolver(userInfoSchema),
  });

Form: Notice I am using template literals for registering each input. It took me forever to figure this out. So far this is the only way I've been able to get the data to output correctly (via react-hook-form's 'watch' method).

<fieldset>
      <legend>Practicing fields of engineering</legend>
      {fieldsOfEng.map((field, i) => {
        return (
          <div key={field.id}>
            <div>
              <input
                {...register(`professions.${i}.name`)}     <--REGISTERED HERE
                value={field.name}
                type="checkbox"
              />
              <div>
                <input
                  {...register(`professions.${i}.experience`)}    <--REGISTERED HERE
                  type="number"
                  value={field.experience}
                  placeholder="Yrs Experience"
                />
              </div>
            </div>

            <div>
              {errors.professions && (
                <p>
                  professions:
                  {errors.professions.message}
                </p>
              )}
            </div>
          </div>
        );
      })}
    </fieldset>
🌐
Zod
zod.dev
Intro | Zod
import * as z from "zod"; const User = z.object({ name: z.string(), }); // some untrusted data... const input = { /* stuff */ }; // the parsed result is validated and type safe!
Discussions

how can I validate an array of objects where each item should contain only one property ?
how can I validate an array of objects where each item should contain only one property ? More on github.com
🌐 github.com
1
1
March 29, 2023
Validate items uniqueness in z.array
I believe a lot of people could use this. i tried searching for opened issues regarding this but couldn't find anything other then this ongoing discussion. if this is already worked on i would ... More on github.com
🌐 github.com
3
September 21, 2025
Looking for help (or examples) setting up zod discriminated union schema to work with react-hook-form.
Try defining level like this when the type is "other": level: z.null().optional().default(null), So you're full schema.tsx would be: import { z } from "zod"; export const typeDiscriminatorSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("developer"), level: z.number().min(1).max(5), }), z.object({ type: z.literal("other"), level: z.null().optional().default(null), }), ]); export const personSchema = z .object({ id: z.string().min(2), name: z.string().min(2), }) .and(typeDiscriminatorSchema); export type Person = z.infer; More on reddit.com
🌐 r/reactjs
12
3
April 4, 2024
Please help - deadline tmrw: How to dynamically add array of objects to React Hook Form (TS + ShadCN + Zod)?
usefieldarray should only be used with array of objects. RHF automatically assigns an id prop if it doesn't exist on each object, and not following that rule can cause a bunch of issues. You can pass validation rules on the usefieldarray but it doesn't always work as expected. The trick with RHF is to use controlled components (using the register or Controller) and let the library manage the state of the form. In other words, in most cases you shouldn't have to use onChange, unless you have interdependent components. What works really well when using a 3rd party is to wrap the components with a Controller (or the hook). I'm not sure about those ShadCN components if they are made explicitly for RHF. One thing to note also is you're doing your validation on the onSubmit, there's other modes in the useForm, onBlur, onChange, onTouched. Often times you'll need to do some mapping when settings the default values, and then remap to what your server expects when submitting. For example for the arrays if they are primitive you need to map them both ways to objects. I would very much like to be more helpful but I'm on my phone, hopefully I put you on some tracks. Good luck! More on reddit.com
🌐 r/react
9
9
February 16, 2024
🌐
Tecktol
tecktol.com › home › zod › zod arrays: from basics to array of objects validation
Zod Arrays: From Basics to Array of Objects Validation - Tecktol
March 30, 2026 - For full examples and edge cases of arrays using .min(), .max(), and .length(), check out Edge Cases of Arrays with Length Constraints. Zod goes beyond static validation by offering tools to transform and refine array data dynamically.
🌐
Nicoespeon
nicoespeon.com › en › 2026 › 03 › decoding-arrays-with-zod
The Proper Way to Decode Arrays (with Zod) — @nicoespeon's blog
March 23, 2026 - z.array(SomeSchema) is the go-to way to validate arrays in Zod. But it has a catch: if any item fails parsing, the whole array is rejected.
🌐
Chrisgriffing
chrisgriffing.com › blog › custom-zod-oneof-validator
Custom Zod oneOf validator | Chris Griffing
June 28, 2024 - If you want to validate for a value being from an array you might use z.enum. However, if you read the docs for Zod enums you might notice that they require you to use z.enum directly or you can pass an array to z.enum as long as you define the array as const.
🌐
Telerik
telerik.com › blogs › zod-typescript-schema-validation-made-easy
Zod + TypeScript: Schema Validation Made Easy
November 3, 2025 - The PersonSchema contains the AddressSchema as a nested property, demonstrating how complex data structures can be validated recursively. Zod automatically handles array validation with z.array() and provides default values with .default().
🌐
StudyRaid
app.studyraid.com › en › read › 11289 › 352183 › creating-array-schema-validations
Creating array schema validations - Zod
Zod allows you to transform array ... arr.map(str => str.toUpperCase()); }); // Example usage const input = ["hello", "world"]; const transformed = transformedArraySchema.parse(input); // Result: ["HELLO", "WORLD"]...
Find elsewhere
🌐
Tighten
tighten.com › insights › form-validation-with-type-inference-made-easy-with-zod-the-best-sidekick-for-typescript
Form Validation with Type Inference Made Easy with Zod, the Best Sidekick for TypeScript | Tighten
March 28, 2024 - Represents an array of items being purchased. Each item includes an ISBN (must be a valid ISBN) and quantity (an integer between 1 and 5). ... Requires the customer's card number (must be a valid credit card number), expiration date (in the ...
🌐
Medium
rasitcolakel.medium.com › exploring-zod-a-comprehensive-guide-to-powerful-data-validation-in-javascript-typescript-2c4818b5646d
Exploring Zod: A Comprehensive Guide to Powerful Data Validation in JavaScript/TypeScript | by Raşit Çolakel | Medium
June 11, 2023 - Zod tries to infer as much as possible, so you don’t have to write everything out. For example, if you pass a string to z.number(), Zod will infer that you want a schema that validates numbers, not strings.
🌐
GitHub
v3.zod.dev
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
🌐
Zod
zod.dev › api
Defining schemas | Zod
Complete API reference for all Zod schema types, methods, and validation features
🌐
GitHub
github.com › colinhacks › zod › discussions › 2316
Validate items uniqueness in `z.array` · colinhacks/zod · Discussion #2316
Another problem with z.sets I ran into was that it ran into "expected set, received array" errors when trying to parse data from an api. I'm not sure if that is a bug, but I use the following now: export function zodUniqueArray<Schema extends ZodSchema, K>( schema: Schema, idSelector: (item: Schema['_output']) => K = item => item ) { return z.array(schema) .refine( items => { const ids = new Set<K>(items.map(i => idSelector(i))); return ids.size === items.length; }, 'array-items-must-be-unique' ); }
Author   colinhacks
🌐
GitHub
github.com › colinhacks › zod › issues › 5267
Validate items uniqueness in z.array · Issue #5267 · colinhacks/zod
September 21, 2025 - the general idea is allowing to validate certain properties or the entire object as unique which will validate all properties in that array and will alert for duplicate values.
Author   colinhacks
🌐
Turing
turing.com › blog › data-integrity-through-zod-validation
Schema Validation with Zod in 2025 | Turing
February 21, 2025 - Zod allows us to provide custom validation logic via refinements. An example of where this might be needed is checking whether a password field and the corresponding confirm password field are the same.
🌐
DEV Community
dev.to › arafat4693 › learn-zod-in-5-minutes-17pn
Learn "Zod" In 5 Minutes - DEV Community
May 7, 2023 - All types in Zod have an optional options parameter you can pass as the last param which defines things like error messages. Also many types has validations you can chain onto the end of the type like optional
🌐
LogRocket
blog.logrocket.com › home › schema validation in typescript with zod
Schema validation in TypeScript with Zod - LogRocket Blog
July 30, 2024 - A Zod record allows you to define schemas with specific types for both their keys and values. Let’s take an example of a shopping cart that is expected to contain a list of products with the number of items ordered for each product.
🌐
The Fish Shell
mvolkmann.github.io › blog › zod
Zod
For example, the following both specify an array of integers: z.array(z.number().int()); z.number().int().array(); To generate a TypeScript type from a Zod schema object, use z.infer.
🌐
Contentful
contentful.com › blog › react-hook-form-validation-zod
Learn Zod validation with React Hook Form | Contentful
April 23, 2026 - ... In the above example, userSchema defines a validation for a nested user object, and highScoresSchema defines an array where each element has a user field validated with the userSchema and a score field which must be a positive number.