form icon indicating copy to clipboard operation
form copied to clipboard

Running onSubmit validators for Linked Fields for array values

Open vonazt opened this issue 11 months ago • 1 comments

I have a Zod schema like this:

z.array(
  z
    .object({
      value: z.string(),
      primary: z.boolean()
    })
    .refine(
      ({ primary, value }) => {
        return !(!primary && value === '');
      },
      {
        message: 'Value cannot be empty if primary is not checked',
        path: ['value']
      }
    )
);

I have attached it to a schema like this:

const emailSchema = z.object({
  email: z.array(stringSchema),
});

I am using that schema on a form like this:

 const form = useForm({
    ...,
    validatorAdapter: zodValidator(),
    validators: {
      onSubmit: emailSchema
    }
})

On the form.Field for the email$[{i}].value i have this:

 <form.Field
      name={selector}
      validators={{
        onChangeListenTo: [`email$[{i}].primary`],
      }}
    >

The issue is that it does not revalidate the field when I select the primary checkbox on the primary field, because I don't have an onChange validator set for the form. However, I don't want the validators firing on every onChange event.

In the primary form.Field I can do something like:

 <form.Field
          name={`email${[i]}.primary`}
          listeners={{
            onChange: () => {
              form.validateArrayFieldsStartingFrom(`email`, 'submit');
            }
          }}
        >

But this doesn't give me as much control over which fields I want to validate. Ideally onChangeListenTo: would also have a callback option where I could specify the validation cause or something similar?

vonazt avatar Jan 16 '25 12:01 vonazt

If what you want is only validate on submit (I'm not sure of your use case), does setting canSubmitWhenInvalid: true solves your use case ?

G-Ray avatar Aug 01 '25 12:08 G-Ray