React Hooks way of validating a Form

Saravanan Ramupillai
2 min readFeb 14, 2019

I know you are super excited with new react hooks and building cool applications. Here I am going to show you how I validated a form built with hooks using hooks in a cleaner (opinionated) way.

I am not using any library, I wrote two tiny generic validation components using hooks that do the all major heavy lifting for form validation and simplifies life. Here is the demo. Here is the source of the validation components.

If you have faced the problem of validating a form and you ended up using a library, these two simple components will give you an insight into doing validation yourself without any library.

My validation util has following major components :-
1. Validator Component (which is responsible for validating individual form field value)
2. Validation Component (which is responsible for maintaining overall validity of form)
3. ValidationHelper (not a component but a helper object with methods to do all basic validation on form value, you could write your own helper for your need)

If you see the registration.form.jsx file in the above sample code, it is so straightforward to see how to use these components.

How to use Validator component:
Validation component has the following signature.

It is self explanatory, take a look at props of validator, it expects fieldName, fieldValue to validate, list of validation functions which will be called to check whether the value is valid or not and finally a callback function to notify when the field value is invalid. Callback function will be called with error object with “fieldName” as key if it’s value is invalid.

How to use Validation component:
Validation component does not takes any props, all you need to do is that, just take ref of it and call the validate method on it. It will give you the object overall form validity.

And that’s it, validation for the form is done. So simple right.

Feel free to try it out and share your thoughts.

--

--