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!