How to make correct object for zod for schema with Nested input name with react final form?

1.5k Views Asked by At

I have a form and I am mapping through inputs(which the number of inputs can increase or decrease based on user preference). I want to be able to validate the inputs with zod but I'm having alot of trouble.I used react final form naming for the inptu names https://final-form.org/docs/final-form/field-names

ex. of the form

     const [filterList, setFilterList] = useState(
    (initialValues !== [] && initialValues) || [{ filter: "" }]
  )
  const verifyInput= () => {
    return z
      .object({
        filters: z.array(
          z.object({
            field: z.object({ label: z.string().min(1), value: z.string().min(1) }),
            conditions: z.object({}),
          })
        ),

      })
  }

  return (
    <Form    
     schema={verifyInput()}>
      {filterList.map((index) => (
         <input
          id="filterTypes"
          name={`filters[${index}].operator`}
          size="sm"
          type="text"
        />

        <select
          id="filterTypes"
          name={`filters[${index}].field`}
          placeholder="Field"
        >
         <option value="volvo">Volvo</option>
         <option value="saab">Saab</option>
       </select>


      <select
        id={index}
        size="sm"
        name={`filters[${index}].conditions`}
        placeholder="Operator"
      >
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
      </select>
      ))}
      <RemoveAllFiltersButton handleFilterRemoveAll={handleFilterRemoveAll} />
      <Button
        onClick={hanldeFilterAdd}
        leftIcon={<FiPlus />}
      >
        Add Filter
      </Button>
    </Form>
  )

it tried above and nothing is happening to inputs. I was expecting for the input to be highlighted red and required be there but nothing happens. enter image description here

1

There are 1 best solutions below

1
ptim On

Suggest using dotted notation rather then the array style:

<input name={`filters.${index}.operator`} />

Just saw this (stale) question in passing, and I'm using hook-form, not fianl form.. but suspect it may be similar..

Consider referring to the zodResolver source for clues: https://github.com/react-hook-form/resolvers/blob/master/zod/src/zod.ts#L13