TanStack / TanStack/form

Running onSubmit validators for Linked Fields for array values

Open
#1,116 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

type: enhancement v1 v2
Dominant language
TypeScript
Stars
6.7k
Forks
682
Avg merge
5d 18h
Merged PRs (30d)
7

Description

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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the form.Field validators onChangeListenTo and the primary field's onChange listener, then compare their behavior with form.validateArrayFieldsStartingFrom using the 'submit' cause. Define the requested callback or equivalent behavior so linked fields can be selectively revalidated with a chosen validation cause, and verify it with array fields using onSubmit validators.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.