Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zod validation for an array of objects

I am trying to add validation for a form that has a checkbox selection with a number input next to each checkbox. A user selects a profession checkbox and then enters the number of years of experience they have in the input next to it. The array looks like this (experience has a default of 1):

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

This is how the schema would look if I was just verifying that the user selected one of the options in my professions array

export const userInfoSchema = z.object({
  professions: z
    .string()
    .array()
    .refine((val) => val.some(profession => 
      fieldsOfEng
        .map((field) => field.name)
        .includes(profession)))
})

with the input being registered via react-hook-form like:

{fieldsOfEng.map((field) => {
     return (

     <input
      {...register("professions")}
      value={field.name}                               
      type="checkbox"
     />

   )}

--------------------WHAT I WANT:

I'd like to add an 'experience' field to my schema so I it would look something like (but this isn't correct):

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

And I think my form would look something like:

{fieldsOfEng.map((field) => {
     return (

     <input
      {...register("professions.name")}
      value={field.name}                               
      type="checkbox"
     />

     <input
      {...register("professions.experience")}
      value={field.experience}                               
      type="number"
     />

   )}

I can always experiment with the form but my main concern is the schema.

like image 313
tdev Avatar asked Dec 05 '25 09:12

tdev


1 Answers

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)
like image 99
Ark Avatar answered Dec 07 '25 21:12

Ark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!