More

    React Form Validation: Here’s How to Do it

    Introduction About React Form Validation:

    Being a developer, it is generally suggested that it is usually best not to reinvent the existing wheel. So, in order to implement a solution the first step is always to look for the pre-existing solutions to the same problem and that is what React is all about! It allows us to create components that are reusable so that there is no need to repeat ourselves in the code. In React, form validation allows the error message to be displayed in our application in the case when the user did not fill out the form correctly with the type of input expected from them. 

    In this article, we will take a look at some of the most commonly used solutions for form validation and management in React. Join us as we walk through to add custom form validation in our React application in just a few simple steps. After reading this article you will be able to create your own custom form validation in the React components present in our application. 

     

    Code:

    Now we are going to see a code below that assumes that the user is familiar with the elements and procedures that are needed to make a React form. In the handleChange function, form validation rules are applied that are responsible to handle the inputs from the users.

    We’ll show and explain the code line-wise. As soon as you click the create button, the console tab shows if the form is valid or not. The lines of code are explained below:

    Line 1-5: 

    The validEmailRegex variable holds the rules of the Regex in order to check whether the given input is a valid email or not.

     

    Line 6-10:

    The function validateForm is there to check whether any of the input fields present have any error or not. If an error is observed then the function outputs it over the console.

     

    const validateForm = errors => {

      let valid = true;

      Object.values(errors).forEach(val => val.length > 0 && (valid = false));

      return valid;

    };

    Line 32-52:

    In the handleChange function, the actual rules of validations have been applied. We can see that in the function there is an implementation of a Switch-case in it which rules that are specific to the input field are applied. As for instance,  if fullName is the input field ( in lines 33-38), then the function will check the length of the value in that field. Whereas it encounters that the length of the input is less than 5, it will automatically set the error message of the field associated with it. Else, the error message for the field associated with it will be set as an empty field.

    Adding in React:

    In React, a form is added just like any other elements are added. For example, we’ll create a form that will allow the user to enter their names:

    Different React Form Validation Libraries:

    Being a developer, it is usually in our best interest if we don’t spend much time reinventing the wheel all over again. This is why our first step for the implementation of a solution is in looking for pre-existing solutions. And this is what makes us use React because of the ability to create components that are reusable so that we do not end up repeating the same thing again and again. So let us take a look at some of the popular solutions that already exist for management and validation of forms:

    Formik:

    How can the roundup on React Form Validation solutions be complete without Formik? Formik is basically the most popular library in React for the building and managing of React forms. It has over twenty-two thousand stars on Github which talks for the popularity of Formik. If you are looking for something scalable and performant that will help you with forms with minimal API the Formik is the answer.

    Formik can be used for handling form state, validation and even error handling. Formik supports the schema-based form validation through the library of Yup. It does not use external state management such as Redux for managing the form state. The React Formik is compatible with both React Native and React Native Web and it is just 15kb in size.

     

    React Final Form: 

    If you are looking for a framework-agnostic form validation library with zero dependencies then React Final Form is the way to go. The original name of the library is Final Form and React Final Form is the wrapper for React. React Final Form is subscription-based so that only the specific field of a form gets updated when we update the final state. We have two ways for the validation of forms using React final Form and the two ways are record level and Field level. The way your form will be validated depends totally on the complexity of your form. If the form is fairly simple then it is a good idea to stick with field-level validation but if it is otherwise then-record level validation must be used.

    React Final Form does not depend on any libraries. It allows us in managing which of the form elements gets notification of changing form state which makes React Final Form very performant. It supports React Hooks and also the schema-based validation through the Yup library. It is also extremely lightweight.

    Uniform:

     This is a performance-centered form library meant to React and Uniform does so by the use of controlled form components. This requires you to create your very own custom component where useField Hook is used for accessing the field data and the methods that are there for the interaction with the field. Uniform supports the React Native by the use of @uniform/mobile package and it uses HTML elements instead of custom components. Support for complex form structure is also present and can be accessed by the use of dot notation for the input name. 

    React Form:

    Hooks are provided by React Form for the managing of form state and validating the forms in React. The way React Form is used is very much similar to the way how Uniform is used. So in React Form, we first have to create a custom field component in which the use field Hook is used. By doing this, we are provided with properties which help us in storing the field errors. It supports React Hooks by using useForm and also uses the concept of memoization for faster re-rendering. It is only 4.5kb so it is also very light in weight.

    React Hook Form: 

    It is a very lightweight form validation library for React. It uses Hooks mainly for the addition of Form validation to HTML elements that are there for input. This is a very modern library for validation of a form and is very performant and easy to use. Out of all the libraries that we have talked about until now, React Hook Form requires you to write the least amount of code for you to use it. It is even only a two-step process of using the Hook and adding the reference to the fields that you want. It makes use of controlled validation pf form for making the performance optimal and it even aligns itself with the existing HTML standard for the validation of a form and for this purpose, it uses rules like requires, max, matter, and so on.

    React Hook Form also supports React Native by simply substituting HTML form elements with React Native equivalent form elements. It has no dependency on any other library and it even provides us with the ability to isolation components and renders for performance improvements.

    React Hook Forms even has a form builder utility if we want to create trivial forms quickly. It supports the schema-based validation with the help of the Yup library. It is user friendly because the documentation is documented and has lots of examples on how to use it.

    Conclusion:

    In this article, we have taken a thorough look into understanding React Form Validation. We have also taken a look at some of the most popular and useful React Form libraries that exist today. It can help us have a great time invalidating our form. It can be easily observed that most of the libraries. Out of all the libraries we have talked about, each one has its pros and cons. It greatly depends on the needs of the developer on which library to use.

    But in any case, one can never go wrong with certain well-known libraries such as the Formik. React Final Form or even React Hook Form. In this article, we have simply seen a round-up of some of the Form management libraries that are there for React.

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here