How to get form validity without submitting it or triggering field errors #713
-
Hello, I am working on a Nextjs project and I have a case where I want to know the validity state of the form at any moment to enable/disable my submit button. I know there is the What I tried is to use a custom This solution works but it requires to use the
How it is used in my button
Is there way I could get live data of the form validity without submitting it or triggering field errors ? Here is a code sandbox with the solution I tried I think the most important thing to know is if all required fields have been filled, not if they really are zod schema compliant, otherwise there is a risk we cannot click on the submit button when we finished typing the last required field but have not yet blurred |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Usually, I would propose to not disable the submit button at all but trigger the form validation and focus the first field with an error on submit. This is what browsers do by default. There are some UX pitfalls with disabled submit buttons to think about, see https://www.smashingmagazine.com/2021/08/frustrating-design-patterns-disabled-buttons/. If that would be acceptable to your requirements your problem would just disappear all-together. If that doesn't fulfill your specific requirements, you could look into using parseWithZod with current conform/packages/conform-dom/formdata.ts Line 251 in 6b98c07 All in all, it's a bit complex and involved. Maybe others have better suggestions? :) I would usually opt for not disabling submit buttons to give the user the possibility to figure out what the missing pieces are. One more observations: form.valid simply reflects if there are currently any errors in the form state. So it reflects the result of parseWithZod in the onValidate fn. It does not depend on a submit unless you configured that the form should validate only onSubmit. If the onValidate fn never ran, e.g. because the user has not interacted with the form yet, then it will be true because form.allErrors will be empty. |
Beta Was this translation helpful? Give feedback.
Usually, I would propose to not disable the submit button at all but trigger the form validation and focus the first field with an error on submit. This is what browsers do by default. There are some UX pitfalls with disabled submit buttons to think about, see https://www.smashingmagazine.com/2021/08/frustrating-design-patterns-disabled-buttons/. If that would be acceptable to your requirements your problem would just disappear all-together. If that doesn't fulfill your specific requirements, you could look into using parseWithZod with current
form.value
converted to a FormData object. This would allow you to validate the validity of your form independent of the onValidate handler and thu…