TanStackT
TanStack11mo ago
6 replies
popular-magenta

Duplicate Errors when using same Schema for onChange and onMount validation

Hello! I'm trying to run the same validation onMount and onChange:
const simpleFormSchema = z.object({
  firstName: z.string().min(4, "must be longer than 4 characters"),
  lastName: z.string().min(4, "must be longer than 4 characters"),
});

const simpleFormOptions = formOptions({
  defaultValues: {
    firstName: "",
    lastName: "",
  },
  validators: {
    onMount: simpleFormSchema,
    onChange: simpleFormSchema,
  },
});


As soon as i start typing in the "firstName" Field I get the error for "lastName" twice.

I thought i might have to start by clearing all errors in the onChange handler but I have no Idea how i could "compose" a custom onChange validator function with a StandardSchemaValidator.
Somthing like:
  validators: {
    onMount: simpleFormSchema,
    // onChange: simpleFormSchema,
    onChange: ({ value, formApi }) => {
      const errors = simpleFormSchema["~validate"](value);
      formApi.setErrorMap({
        onMount: null,
        onChange: errors
      });
    },
  },
Was this page helpful?