In the early days of the internet, HTML forms were the first way of interacting with websites. The internet has come a long way since, but forms are still an essential component of any web application.

In React, you can validate forms in many different ways. There are some libraries out there that intend to make this task easier for you.

However, doing it yourself has a few advantages: You have control over the API layout, and since you probably don’t need all the features that these libraries come with, you also save some bandwidth. More importantly, though, you get a deeper understanding of the mechanics behind some of these libraries.

In this tutorial, I want to show you how you can create a custom hook that you can use to validate all of your forms. The code for this doesn’t need to be huge; in fact, the TypeScript version counts less than 100 lines.

The way I designed this hook fits my personal needs, but your mileage may vary. If you use a different implementation or have suggestions, please leave a comment, as I’m always looking for improvements.

  • What we’re building
  • Demo
  • Tutorial
  • Adding TypeScript
  • Conclusion

Please note that in this tutorial, I focus on client-side validations. However, you can easily adapt the hook to validate your data on the backend as well.

What we’re building

In this tutorial, we’re going to build a registration form with validation on the frontend.

We’re going to create a hook that will be able to do the following:

  • Validate user input
  • Update form data
  • Handle form submission

#react #typescript

Form validation with React Hooks WITHOUT a library: The Complete Guide
8.05 GEEK