IdoPesok/zsa

Send zod validation errors

Closed this issue · 2 comments

Hello!

I've been working on my own trpc like server action library then came across this, it's basically the exact api I had, so thinking I might as well use this.

The only thing im missing from this library is the ability to return formatted validation errors that comes from zod i.e. result.error.flatten().fieldErrors when safeParse fails.

Looking at your code I see that you just throw a custom Error when this fails but the response to the client is stringified json, I guess I could parse it on the frontend but my ideal api would be something like this:

export function LoginForm() {
  const { execute, data, error } = useServerAction(login)
  return (
    <form action={execute} className="space-y-2">
      <FormField
        required
        minLength={3}
        label="Email address"
        name="email"
        errors={error?.fieldErrors?.email}
      />
      <FormField
        required
        minLength={8}
        label="Password"
        name="password"
        type="password"
        errors={error?.fieldErrors?.password}
        placeholder="********"
      />
      <FormError error={error.formError} />
      <FormButton className="w-full">Login</FormButton>
    </form>
  )

Wondering if you've run into similar needs or if theres another way of achieving something similar this? trpc has the formatError function which allows you to customise the error response so I could add fieldErrors as a custom key, and formError for general errors. What do you think?

Thanks for the good work!

Hi, thank you for this recommendation! If the error type is INPUT_PARSE_ERROR then the following typed fields will be present on errors: fieldErrors, formattedErrors, and formErrors

Will push soon : )

Screen Shot 2024-05-29 at 8 30 45 AM Screen Shot 2024-05-29 at 8 31 08 AM Screen Shot 2024-05-29 at 8 31 36 AM

This will also add ability to narrow down the error to INPUT_PARSE_ERROR, and get back the defined zod error fields.

Screen Shot 2024-05-29 at 8 39 21 AM