Skip to content

Returning an other data type as error message #5323

@saman2007

Description

@saman2007

Hello guys.
In my Next.js project, I implemented internationalization by myslef (without using any packages). And I use zod with react-hook-form.
Here is the problem:
my locale messages can be like this: "Text must be at least {n} character(s)"
and with t method, i can get the text base on the locale like this: t('key', {n: 1})
But when I tried to make some error messages in zod config like this: {message: {key: "key", data: {somedata: data}}}, I realized that the type of error messages in zod, is either string or null.
So do you have any idea about how I can change the error message format in zod config? I remember that I implemented this kind of error messages using yup but with zod, I have no idea about how to do it.
Here is what I want to do but the declared types for zod, cause TS error and I can't simply ignore them because there could be something important about error types in Zod’s internal code internal code that I don't know about.

// zodConfig.ts
import { z } from "zod";

z.config({
  customError: (iss) => {
    switch (iss.code) {
      case "too_small":
        return { message: { key: "too_small", data: { n: iss.minimum } } };

      default:
        return iss.message;
    }
  },
});

export { z };

And I want to use error messages in my form fields that are with validation, like this:

const InputRHF = ({
  name,
  ...props
}: React.ComponentProps<"input"> & { name: string }) => {
  const { register } = useFormContext();
  const { errors } = useFormState({ name });

  const params = useParams<Params>();
  const { t } = getTranslations(["zod-errors"], params);

  const error = errors[name]?.message as
    | { key: string; data: Record<string, string | number> }
    | undefined;

  return (
    <>
      <InputUI
        aria-invalid={!!error}
        {...props}
        {...register(name, {
          onBlur: props?.onBlur,
          onChange: props?.onChange,
        })}
      />
      <FieldError error={error ? t(`zod-errors.${error.key}`, error.data) : undefined} />
    </>
  );
};

One solution that I've found is to use JSON.stringify and JSON.parse but it feels like a workaround and I would prefer not to use it until I have no choice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions