react-hook-form: Pass original validation error as an optional parameter of FieldError
Is your feature request related to a problem? Please describe.
It’s currently not possible to access the original error thrown by validation libraries. This makes it very inconvenient to plug and play translation libraries in the react eco system.
For example, Zod throws the following validation error:
ZodError: [
{
"code": "too_small",
"minimum": 3,
"type": "string",
"inclusive": true,
"message": "error.nameMin",
"path": [
"name"
]
}
]
but only this part is returned from zodResolver:
name: name,
message: "error.nameMin",
ref: input,
type: "too_small",
Information like minimum: 3 is lost, so it’s impossible to wire up a hook based solution like react-18next to create dynamic translations like:
t(error.message, { minimum: error.minimum }
Describe the solution you’d like
At the Zod core level, the solution I’d like is implemented here. It creates a “slot” to allow for an arbitrary error specific to a library to be returned as part of FieldError
This would then allow us to rewrite zodResolver to return the original error as part of the FieldError, which in turn would allow us to write something like:
export const FormError : FunctionComponent<{ error: FieldError }> = ({
error,
}) => {
const { t } = useTranslation('formErrors');
return error ? <span>{t(error.message, error.validationError)}</span> : null;
}
Describe alternatives you’ve considered
The above code already works if you dont care for typescript. In this Poc Repository I achieve what I want by implementing my own ZodResolver, which is just a copy paste of the existing one, with 2 lines changed. So that was one option.
Another option would be to have the translations being done at the schema, like
z.object({
name: string().min(3, t("error.message", { minimum: 3 })
})
But this implies one of 2 things, either we have validation schemas getting created inside the react render cycle (because t is hook provided function) or we risk using a stale t function from the non hook provider.
Additional context
This idea is loosely based on this post: https://github.com/react-hook-form/react-hook-form/discussions/3808#discussioncomment-261851
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 5
- Comments: 22 (14 by maintainers)
It seems like we’re talking in general about some potential use-case we haven’t come across yet. IMO, let’s implement the
as it’s the most useful info for error handling missing from whatever the field of possibilities with these validation libs. It solves the case where we need to have validation params for i18n, which was the initial request. Next time the question comes up with some additional field needed from error object of some lib, we can have a look at how necessary it is to provide the full object.
Keep in mind that we don’t wanna bloat the library with code that would further couple it with some tech. The resolvers solution was designed to be a common interface to integrate with whichever validation lib you want, not to make use any specific validation feature from a specific lib. Just the way date-io abstraction is. See this point on the matter as well
Your option would indeed get us out of the situation of the minimalist example, and I have nothing against it. I understand the appeal of having RHF abstracting away the different errors from different validators onto a common interface.
That being said I think providing us with a way to interact with the “native” error would be beneficial. If not for anything else,
Zod(And yup), provide ways to create custom validators with arbitrary parameters being returned for the error message. And we seem to be a fan of those in the office 😉 So it would just make it more future proof to have a way for us to untangle ourselves.I see your point. As a workaround, you can create a Context to avoid passing down the schema manually as, I’d think, your schema is mostly static making use of
.refine(), so it won’t create a performance overhead. But, yeah, it’s no elegant abstraction and we should continue to think about a better solutionThanks for all the feedback. I understand where are your concern coming from. However, there is a general direction We need to take consider very carefully for the library not only to support or in favor of any schema validation library (there is build-in as well), so whatever decision we make need to fulfill both categories. This is just like another tradeoff we are making every day in software development. One of the reasons the error messages need to have a proper interface is that we need to set up the standard and why we are building this library in the first place. Eg, if you are switching schema validation libraries and nothing should break. If you are using typescript, then if we can have some sort of type guard would be nice but in this case, I would not die for the type-safe, but at least the shape is important. So just like @Moshyfawn mentioned, our goal is to try to solve the most important missing piece first, then progressively enhance the requirement, hopefully, it will cover most use cases. I understand this may not be the desired outcome that you want, but I believe this is a better approach to this problem.
So what’s next? We will wait for the feature required to see more upvotes, then start to introduce the following two attributes to the errors object:
receivedandexpected, if there are more common usage, we can consider introducing more error interface.Don’t get me wrong, I totally see your point. Having the same
event.nativeEventonly for RHF for validation schemas would mean no more “expose this field from this validation lib”, which would make for great DX and more tech integration opportunities. At least, on paper.I’m more concerned about the potential coupling and type-safety issues + the way we talk about how unified error output (the solution @bluebill1049 proposed) wouldn’t cover all potential use-cases; ATM it sounds like a very blown out feature request. The proposed solution covers the use-case described. The idea behind what I was saying previously is to potentially iterate on the solution, but to start with having the “missing” fields add, currently preventing from moving forward with the described feature.
To sum up, there’s a scope RHF / @hookform/resolvers have and we outta closely consider every piece of code we take in to maintain in the future. I’m not trying to dismiss your request, but rather pushing for having some solution built that would improve the situation for the use-case, while we’re considering our next steps / discussing other potential solutions to apply in the future.
how could make
validationErrortype-safe with all the other validation schemas? One of the reasons why I purposed a fixed return type. Don’t forget build in validation as well.that is exactly what I propose! 😄 I just called it
validationErrorinstead ofnativeError.I might be oversimplifying and not thinking it though, but what if we have a
nativeErrorfield along side the ones @hookform/resolvers already returns with the actual validation lib error object? Kinda like React hasevent.nativeEventon theeventobject