Trusted answers to developer questions

React form validation

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

Code

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')
);

Explanation

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.

  • Lines 3-5: The validEmailRegex variable holds the regex rules to check whether or not the given input is a valid email.
  • Lines 6-10: The 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.
  • Lines 32-52: The actual rules of validation are applied in the 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.

RELATED TAGS

react
validation
form
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?