Simple form validation for your React app

Sonjoy Datta
2 min readMay 7, 2020

--

ReactJs Form Validation

Are you looking for an easy way to validate your ReactJs form? So, let me show you how this simple part can be done in the easiest way. I have used the Bootstrap framework with React. But, you can do it without using the Bootstrap.

The idea behind validation

You have mainly two components useForm and the validation rules.

You are able to reuse the useForm component for all different forms but, you need to create different validation rules for the different forms.

How useForm works?
It will manage all the values, errors, and action handlers of a form. Then, it will callback a function to the parent component if the form has no errors and this function will help you to make the server request.

In this way, those inputs will be validated which has the required attributes. It will work in two ways when you will change your input and when you click on the form submit button.

What is the validation rule?
Validation rules verify that the data a user enters in a record meets the standards you specify. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”.

The component of this validity rule must be different for different forms. But, it is okay to use the same rules for the same form when adding and updating data.

Adding to form,
See the following “Sign In” form to check how these are works with the parent component.

You need to remove the “required” attribute from the input field if you do not want to check the rule for any specific field. Also, you need to add the “noValidate” attribute to avoid the default validity of the browser.

Thank you for reading!

--

--

Sonjoy Datta

A Software Engineer from Dhaka, Bangladesh with experience in Frontend development using modern JavaScript-based frameworks (ES6)