Implementing JOI Module in ReactJS
Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.
- It’s easy to get started and easy to use.
- It is widely used and popular module for data validation.
- It supports schema based validation.
Step 1: Create react app using the following command.
npx create-react-app my-first-app
Step 2: Change directory to that folder by executing command :
Step 3: Install the necessary dependencies. Go to the directory ‘src’ and execute command prompt there and run command
npm install joi
File Structure: It will look like the following.
Step 4: Now we will create a form for a customer and add validations to it. Customer Form will contain fields like:
Field Name Validations First Name minimum length=1
Last Name required required PIN Code in range 1000-9999 Date of Birth Born after ‘2001-01-01’
In the below file, we will create a form containing various fields like firstName, lastName, Pin, Date of Birth, and email. Then create a schema then defined Joi validations. If any error is caught, then various div are created to display error.
Step 5: Create ValidationJoiHome component and import CustomerForm here. In this component, simply CustomerForm is imported.
Step 6: Add ValidationJoiHome component in App.js
Step to run the application: Open the terminal and type the following command.