React Js Form Validation has become a lot easier due to the npm packages available, otherwise it would have been a lot more challenging as react js form updation is being dynamically controlled. In this tutorial, we would be using two npm packages react-validation and validator. Here we are creating a signup form with input fields name, email, and phone number. Email validation is been done by using a validator library you can definitely skip the use of validator also and create your own email validation function. Follow the step by step tutorial and also don’t just copy-paste the code, try coding in your IDE for a better idea. So, let’s get started.
We are using npm install react-validation module for the validation. It provides 3 wrapper classes namely-Form, Input, Button that change the behavior of default tags form, input, button. Even some react js original basic forms features might not work efficiently because using a 3rd party module indeed restricts a bit, but in react js this is the easiest way to add validations.
In this example, we are also using validator module for react js form validation in case of email. Installing this is optional and you can instead use your own js email validation function too.
2.Create Validation Methods
We will first import the 3 components of react-validation in the app.js and then validator component for the email. In this react js form validation we are defining required validation, using validator for email and defining phone Number validation where 10 digits are required.
3. Using Validation in Form
The methods are written in app.js and so do the react js validation form in app.js, so both the screenshots are in continuation. As in the code in validations property of the Input tag, we are using required, email, and phone number validations.
The code in index.js would remain the same
4. Run the Code
Now, how the code works is that if name is empty or phone number is invalid or email is incorrect the submit button would remain to be disabled as we are using Button, not button which has a special property in react js form validation and taken care by react-validation module.
npm start to load the application. Based on the same principle create your own methods for validation similarly. Here is link to official documentation https://www.npmjs.com/package/react-validation for reference.
This was a short tutorial on react js form validation which can be done without much knowledge of react js forms also.