Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Running onSubmit validators for Linked Fields for array values #1116

Open
vonazt opened this issue Jan 16, 2025 · 1 comment
Open

Running onSubmit validators for Linked Fields for array values #1116

vonazt opened this issue Jan 16, 2025 · 1 comment

Comments

@vonazt
Copy link

vonazt commented Jan 16, 2025

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@vonazt and others