TanStackT
TanStack2y ago
44 replies
hidden-sapphire

Displaying Validation Messages with Zod in Next.js

I’m having trouble showing validation messages with Zod as the validator in my Next.js project.

Here’s my code:

const form = useForm({
    defaultValues: {
      email: "",
      firstName: "",
      lastName: "",
      password: "",
    },
    onSubmit: async ({ value }) => {
      await signUp(value);
    },
    validatorAdapter: zodValidator(),
    validators: {
      onChange: insertUserSchema,
    },
  });


<form.Field
          children={(field) => <InputGroup field={field} type="password" />}
          name="password"
        />


function InputGroup({ field, ...props }: InputGroupProps) {
  return (
    <div className="flex flex-col gap-3">
      <label className="capitalize" htmlFor={field.name}>
        {field.name}
      </label>
      <Input
        name={field.name}
        onChange={(event) => field.handleChange(event.target.value)}
        {...props}
      />
      {field.state.meta.errors ? (
        <em role="alert">{field.state.meta.errors.join(", ")}</em>
      ) : null}
    </div>
  );
}


I’d appreciate any help. Let me know if you need more details!
Was this page helpful?