How I built an async form validation library in ~100 lines of code with React Hooks

Last updated 80 days ago by Austin Malerba

react

Form 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:

  • Synchronously validate a field and any dependent fields when the field value changes
  • Asynchronously validate a field and any dependent fields when the field value changes
  • Synchronously validate all fields before submitting
  • Asynchronously validate all fields before submitting
  • Attempt async submission and if the form fails to submit, display errors from the response
  • Expose validation methods to the developer so the developer can validate onBlur or at other times that make sense
  • Allow multiple validations per field
  • Disable submission if the form has errors
  • Do not show a field’s errors until it has been changed or until a form submission has been attempted

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.

Read full Article