Input validation in React

In this article, we will show you how to add the validation for form input in React. Here, you will learn how to create a common Input component in React and reuse it for multipurpose.

Demo Application

Output - Input validation in React - Clue Mediator
Output – Input validation in React – Clue Mediator

Steps to validate the input field in React

  1. Create a react app
  2. Create a common Input component
  3. Create a form using the Input component
  4. Output

1. Create a react app

Let’s create a react application using the create-react-app. Here we will add the bootstrap in react.

Reference: How to add Bootstrap in React

2. Create a common Input component

To create a reusable Input component, we need to pass the props like type, name, title, value, onChangeFunc, etc.

In addition, we have to go through a few more props to handle the validation such as isReq, reqType, errorMsg, onValidateFunc.

Input.js

In the above code, we have used the Regular Expression to validate the input field.

Reference: Regular expression examples in JavaScript

3. Create a form using the Input component

Now it’s time to use the Input component in the main component. First of all, we have to define two different state variables called form and error.

In the error state, we have defined the object for each property. The error object contains the following attributes.

  • isReq – For require validation
  • reqType – For special type validation such as EMAIL and URL
  • errorMsg – To render the error message on the screen
  • onValidateFunc – Function to handle the validation

Use the following HTML to render the form in React component.

Let’s put all code together and see how it looks.

App.js

4. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *