React Form Validation
Live Demo: https://react-form-validation.verdi327.now.sh
Form validation can be a pain in the butt. What seems like a relatively straightforward tasks can actually have many moving parts. This article outlines a simple and effective approach which will give your users feedback as they type (not before!) and allow you full control over what validations you want to include and what types of error messages you want to show.
- Make every input a controlled input ? i.e. its value should be set within the component?s state.
- Add onChange handlers to all the form fields. When the value changes, it should trigger a state update.
- After the state update completes, a callback function should fire which checks the validity of the value and then sets another state property flagging the field as invalid or valid. This will display appropriate field error messages.
- Finally, another callback function should trigger which then checks to see if the whole form is valid or not. This is will allow / disallow form submission.
Code Example of the Above Flow
Imagine we have a signup form which contains the following fields ? username, email, password, password confirmation.
We?ll need to follow the four steps in the overview for each form field. Let?s see what it looks like for username where the only validation is that the name must be at least three characters long.
Within the below Gist, I?ve annotated the steps and how they correspond to the above flow discussed.
Username validation flow
To clean up the code a bit, I?ve added an additional functional component called ValidationMessage. The sole purpose of this component is to display the error messages. I extracted the code into another component so we don?t have to fill up our form with repetitive conditional logic.
The code for the ValidationMessage looks like:
Handling error messages
Completing the Form
As you continue to add more fields to your form, you?ll continue this same process. A new field will be saved in state and a corresponding validFieldName flag will be created. Then, your validateForm() function will expand to include this new field within its check to see if the form is valid.
Full Code Example
- Github: https://github.com/verdi327/react-form-validation-demo
- Live Demo: https://react-form-validation.verdi327.now.sh
Form validation ? full example