Form validation in React allows an error message to be displayed if the user has not correctly filled out the form with the expected type of input.
There are several ways to validate forms in React; however, this shot will focus on creating a validator function with validation rules.
The code below assumes that the user is familiar with the procedure and elements needed to make a React form. The form validation rules are applied in the handleChange
function that handles input from users.
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
Upon clicking the Create button, the console tab shows whether or not the form is valid. The lines of code that implement this functionality are explained below.
validEmailRegex
variable holds the regex rules to check whether or not the given input is a valid email.validateForm
function checks whether or not any of the input fields have any errors. If there are any errors, the function outputs it on the console.handleChange
function. The function has a switch-case
implementation in it which applies rules specific to the input field. For example, if the input field is fullName
in Lines 33-38, then the function checks the length of the value in that field. If the length is less than 5, it sets the error message of the associated field. Otherwise, the error message of the associated field is set to an empty field.