React form validation library built under 5kB

Bill
2 min readApr 18, 2019

📋 React custom hook for form validation without the hassle

TL;DR: Introducing a new React Hook library to deal with form validation with an easier and cleaner approach (IMHO).

I have been dealing with forms over the past years, whether it’s a single form submission or multiple steps funnel.

Recently React 16.8 have landed us with Hook, which in my opinion is one the greatest features that React team has been delivered🌹(Thank you). Therefore, I have discovered a new approach to write form validation, potentially a cleaner approach. let me show you the code 🔎

As you can see from the example above, there is no Component have been imported. So instead of having controlled input/select over the form, this approach leverage uncontrolled form input and registering their ref into the React hook form. This allows the hook to have full control and insight over your form elements, and hence this reveal many other benefits:

  1. No external Components required to wrap around inputs, which made the hook library much smaller (5kb gzip)
  2. Because it’s uncontrolled, you are no longer required to have onChange and set value to your input, start leveraging your existing HTML markup.
  3. With Component’s ref been registered into the Hook, you can easily access its ref when an error occurred, and anchors to the particular field.
  4. Much simpler API, because validation occurs at the register level.
  5. Great for performance as input change no longer trigger re-render, check out the performance comparison here.
  6. Easy form state access, since Hook is holding refs for each input. you can easily query the value of them.
  7. Support browser build-in validation ❤️.

Those are my summaries of benefits over using React Hook Form, I think with this approach, things are much simpler (IMHO). Please check out the website for a live demo, I have also built a form builder which allows you to create form and copy/paste code to your environment or codeSandbox to test them out. Many examples also live on the Github page.

I really hope this will make form validation easier, and feel free to leave me with an issue or suggestion on Github (please leave a star if you find it useful 🙏🏻). ❤️ Thank you for reading.

--

--