TanStackT
TanStack8mo ago
10 replies
ordinary-sapphire

Is it expected to have validations run multiple times when submitting a form?

so if I have a zod schema and I want to run more narrow validations without having to parse my zod error schema, is it expected that this onChangeAsync function runs once after the change/debounce and again when the field is submitted? In my current form I am making an API request, but I am essentially making a double request once after the change and another when I submit the form. Am I expected to have these validators run twice if I implement my form this way?

const schema = z.object({
  name: z.string(),
  bio: z.string()
});

const CustomForm = () => {
  const form = useForm({
    defaultValues: {
      name: "",
      bio: "",
    },
    validators: {
      onSubmit: schema
    },
    onSubmit: async ({ value }) => {
      // do api request stuff
    }
  });

  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    e.stopPropagation();

    form.handleSubmit();
  }

  return (
    <form onSubmit={onSubmit}>
      <form.AppField 
        name="name"
        validators={{
          onChangeAsyncDebounceMs: 300,
          onChangeAsync: ({ value }) => {
            if (!value.trim().length) return "Name is required";

            return "";
          },
        }}
        children={(field) => <field.TextField label="Name" />}
      />
      {/* other input field */}
      <form.AppForm>
        <form.SubscribeButton />
      </form.AppForm>
    </form>
  ) 
}
Was this page helpful?