Zod validation with react-hook-form
Is there a way to validate form field for multiple errors simultaneosly? My use case is password strength indicator where I need to validate password for 3 validation criteria (length, contains digit, contains special symbol) at the same time. I am using zod and my schema is like this:
But the problem is that I am only getting 1 error at a time (in react-hook-forms
form.formState.errors
) as I defined above. I tried to use z.union
and even z.superRefine
but to no avail.7 Replies
Found this PR
https://github.com/react-hook-form/react-hook-form/pull/750
Try using criteriaMode instead
GitHub
support multiple errors for ErrorMessage component by kotarella1110...
Add render prop (children prop) with message and messages as arguments!
Related PR: #715
export default function App() {
const { register, errors, handleSubmit } = useForm<{
password: stri...
@alexmartos Do you know how to implement this? I mean I am only getting a single error inside
form.formState.errors
?I made a fast implementation here: https://stackblitz.com/edit/stackblitz-starters-wttzqu?file=app%2Fpage.tsx
Try commenting out
criteriaMode
and it shold only warn about 1 error@alexmartos Oh, I see, thank you! This is really helpful
But this solutions doesn't seem flexible at all
Like if I need some fields to show all errors and other fields to show only first error, then I think I would need to use 2 different
useForm
hooks...If I remember correctly, you always get the first error as normal under ‘error.message’ if you have multiple errors those are under ‘error.types’
So you could use this solution for both all and first
Yes, I see. You are correct this should solve my case