Last updated 3 years ago by Austin Malerba
reactForm validation can be a tricky thing. There are a surprising number of edge cases as you get into the guts of a form implementation. Thankfully, there are many form validation libraries out there which provide the necessary flags and handlers to implement a robust form, but I challenged myself to build one in under 100 lines of code using the React Hooks API (currently in alpha). As React Hooks are still an experimental proposal, this is a proof of concept for the application of React Hooks to implement form validation.
Also, fair warning, the library I build is 100 lines of code, but this tutorial has ~200 lines of code because I need to show how the library is used.
Many form tutorials I’ve seen fail to address three big topics: async validation, field validations that should be triggered when other fields change, and optimization of validation frequency. I am bothered by tutorials that focus on a single use case and hold all other variables constant because that’s not how the real world works, so I will try to hit a variety of use cases.
Let’s aim to satisfy the following:
We will hit these use cases by implementing an account registration form with a username, password, and password confirmation. Below I’ve outlined the kind of interface we’re looking for, we will build a library to satisfy this contract.