Introduction
In this chapter, we will explore how to implement form validation in React. Form validation is crucial for ensuring that user inputs meet certain criteria before being submitted. We will cover both class components and functional components, demonstrating how to validate form fields and display error messages.
Table of Contents
- Basics of Form Validation
- Form Validation in Class Components
- Example: Input Validation
- Example: Complete Form with Validation
- Form Validation in Functional Components
- Example: Input Validation
- Example: Complete Form with Validation
- Key Features of React Form Validation
- Conclusion
Basics of Form Validation
Form validation ensures that the data submitted by the user meets the required criteria. This can include checking if fields are filled out, if the input matches a certain pattern, or if it falls within a specific range. React allows you to implement form validation by using state to manage input values and validation errors.
Form Validation in Class Components
Example: Input Validation
- Create a New File for the Component: In the
srcdirectory, create a new file namedInputValidationClass.js. - Define the Component: Add the following code to
InputValidationClass.jsto create a class component with input validation:// InputValidationClass.js import React, { Component } from 'react'; class InputValidationClass extends Component { constructor(props) { super(props); this.state = { username: '', usernameError: '' }; } handleChange = (event) => { this.setState({ username: event.target.value }); }; validate = () => { let usernameError = ''; if (!this.state.username) { usernameError = 'Username is required'; } this.setState({ usernameError }); return !usernameError; }; handleSubmit = (event) => { event.preventDefault(); if (this.validate()) { alert(`Form submitted with username: ${this.state.username}`); } }; render() { return ( <div> <h1>Input Validation</h1> <form onSubmit={this.handleSubmit}> <label> Username: <input type="text" value={this.state.username} onChange={this.handleChange} /> </label> {this.state.usernameError && ( <p style={{ color: 'red' }}>{this.state.usernameError}</p> )} <button type="submit">Submit</button> </form> </div> ); } } export default InputValidationClass;Explanation:
- The
validatemethod checks if theusernamefield is empty and sets an error message if it is. - The
handleSubmitmethod prevents the default form submission, validates the form, and displays an alert if the form is valid. - The error message is conditionally rendered if there is an error.
- The
- Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theInputValidationClasscomponent:// App.js import React from 'react'; import InputValidationClass from './InputValidationClass'; function App() { return ( <div> <InputValidationClass /> </div> ); } export default App; - Save and View Changes: Save the files and go to your browser. You should see an input field with validation. If you try to submit the form without entering a username, it will display an error message.
Example: Complete Form with Validation
- Create a New File for the Component: In the
srcdirectory, create a new file namedFormValidationClass.js. - Define the Component: Add the following code to
FormValidationClass.jsto create a complete form component with validation:// FormValidationClass.js import React, { Component } from 'react'; class FormValidationClass extends Component { constructor(props) { super(props); this.state = { username: '', email: '', usernameError: '', emailError: '' }; } handleChange = (event) => { const { name, value } = event.target; this.setState({ [name]: value }); }; validate = () => { let usernameError = ''; let emailError = ''; if (!this.state.username) { usernameError = 'Username is required'; } if (!this.state.email.includes('@')) { emailError = 'Invalid email'; } this.setState({ usernameError, emailError }); return !usernameError && !emailError; }; handleSubmit = (event) => { event.preventDefault(); if (this.validate()) { alert(`Form submitted with username: ${this.state.username}, email: ${this.state.email}`); } }; render() { return ( <div> <h1>Form Validation</h1> <form onSubmit={this.handleSubmit}> <label> Username: <input type="text" name="username" value={this.state.username} onChange={this.handleChange} /> </label> {this.state.usernameError && ( <p style={{ color: 'red' }}>{this.state.usernameError}</p> )} <br /> <label> Email: <input type="email" name="email" value={this.state.email} onChange={this.handleChange} /> </label> {this.state.emailError && ( <p style={{ color: 'red' }}>{this.state.emailError}</p> )} <br /> <button type="submit">Submit</button> </form> </div> ); } } export default FormValidationClass;Explanation:
- The
validatemethod checks if theusernamefield is empty and if theemailfield contains an@symbol. It sets error messages if the validations fail. - The
handleSubmitmethod prevents the default form submission, validates the form, and displays an alert if the form is valid. - The error messages are conditionally rendered if there are errors.
- The
- Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theFormValidationClasscomponent:// App.js import React from 'react'; import FormValidationClass from './FormValidationClass'; function App() { return ( <div> <FormValidationClass /> </div> ); } export default App; - Save and View Changes: Save the files and go to your browser. You should see a form with input fields for username and email, both of which have validation.
Form Validation in Functional Components
Example: Input Validation
- Create a New File for the Component: In the
srcdirectory, create a new file namedInputValidationFunction.js. - Define the Component: Add the following code to
InputValidationFunction.jsto create a functional component with input validation:// InputValidationFunction.js import React, { useState } from 'react'; function InputValidationFunction() { const [username, setUsername] = useState(''); const [usernameError, setUsernameError] = useState(''); const handleChange = (event) => { setUsername(event.target.value); }; const validate = () => { let usernameError = ''; if (!username) { usernameError = 'Username is required'; } setUsernameError(usernameError); return !usernameError; }; const handleSubmit = (event) => { event.preventDefault(); if (validate()) { alert(`Form submitted with username: ${username}`); } }; return ( <div> <h1>Input Validation</h1> <form onSubmit={handleSubmit}> <label> Username: <input type="text" value={username} onChange={handleChange} /> </label> {usernameError && ( <p style={{ color: 'red' }}>{usernameError}</p> )} <button type="submit">Submit</button> </form> </div> ); } export default InputValidationFunction;Explanation:
- The
useStatehook is used to create state variables forusernameandusernameError. - The
validatefunction checks if theusernamefield is empty and sets an error message if it is. - The
handleSubmitfunction prevents the default form submission, validates the form, and displays an alert if the form is valid. - The error message is conditionally rendered if there is an error.
- The
- Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theInputValidationFunctioncomponent:// App.js import React from 'react'; import InputValidationFunction from './InputValidationFunction'; function App() { return ( <div> <InputValidationFunction /> </div> ); } export default App;
`
- Save and View Changes: Save the files and go to your browser. You should see an input field with validation. If you try to submit the form without entering a username, it will display an error message.
Example: Complete Form with Validation
- Create a New File for the Component: In the
srcdirectory, create a new file namedFormValidationFunction.js. - Define the Component: Add the following code to
FormValidationFunction.jsto create a complete form component with validation:// FormValidationFunction.js import React, { useState } from 'react'; function FormValidationFunction() { const [formData, setFormData] = useState({ username: '', email: '' }); const [errors, setErrors] = useState({ usernameError: '', emailError: '' }); const handleChange = (event) => { const { name, value } = event.target; setFormData((prevFormData) => ({ ...prevFormData, [name]: value })); }; const validate = () => { let usernameError = ''; let emailError = ''; if (!formData.username) { usernameError = 'Username is required'; } if (!formData.email.includes('@')) { emailError = 'Invalid email'; } setErrors({ usernameError, emailError }); return !usernameError && !emailError; }; const handleSubmit = (event) => { event.preventDefault(); if (validate()) { alert(`Form submitted with username: ${formData.username}, email: ${formData.email}`); } }; return ( <div> <h1>Form Validation</h1> <form onSubmit={handleSubmit}> <label> Username: <input type="text" name="username" value={formData.username} onChange={handleChange} /> </label> {errors.usernameError && ( <p style={{ color: 'red' }}>{errors.usernameError}</p> )} <br /> <label> Email: <input type="email" name="email" value={formData.email} onChange={handleChange} /> </label> {errors.emailError && ( <p style={{ color: 'red' }}>{errors.emailError}</p> )} <br /> <button type="submit">Submit</button> </form> </div> ); } export default FormValidationFunction;Explanation:
- The
useStatehook is used to create state variables forformDataanderrors. - The
handleChangefunction updates theformDatastate when the input fields change. - The
validatefunction checks if theusernamefield is empty and if theemailfield contains an@symbol. It sets error messages if the validations fail. - The
handleSubmitfunction prevents the default form submission, validates the form, and displays an alert if the form is valid. - The error messages are conditionally rendered if there are errors.
- The
- Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theFormValidationFunctioncomponent:// App.js import React from 'react'; import FormValidationFunction from './FormValidationFunction'; function App() { return ( <div> <FormValidationFunction /> </div> ); } export default App; - Save and View Changes: Save the files and go to your browser. You should see a form with input fields for username and email, both of which have validation.
Key Features of React Form Validation
- Controlled Components: Forms in React are controlled by state, allowing you to manage the form data and behavior fully.
- Error Handling: React makes it easy to display error messages and manage validation logic.
- Multiple Form Controls: React supports various form controls, including input fields, checkboxes, radio buttons, and select dropdowns.
- useState Hook: The
useStatehook is essential for managing state in functional components, making it easy to handle form data and validation. - Event Handling: React provides straightforward event handling for form submission and input changes.
Conclusion
In this chapter, you learned how to implement form validation in React using both class components and functional components with the useState hook. We covered the basics of form validation, including input validation and complete form validation. Understanding how to manage form validation is crucial for ensuring that user inputs meet the required criteria before being submitted. This knowledge will help you create robust and user-friendly forms in your React applications.