React Form Validation

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

  1. Basics of Form Validation
  2. Form Validation in Class Components
    • Example: Input Validation
    • Example: Complete Form with Validation
  3. Form Validation in Functional Components
    • Example: Input Validation
    • Example: Complete Form with Validation
  4. Key Features of React Form Validation
  5. 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

  1. Create a New File for the Component: In the src directory, create a new file named InputValidationClass.js.
  2. Define the Component: Add the following code to InputValidationClass.js to 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 validate method checks if the username field is empty and sets an error message if it is.
    • The handleSubmit method 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.
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the InputValidationClass component:
    // App.js
    import React from 'react';
    import InputValidationClass from './InputValidationClass';
    
    function App() {
      return (
        <div>
          <InputValidationClass />
        </div>
      );
    }
    
    export default App;
    
  4. 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

  1. Create a New File for the Component: In the src directory, create a new file named FormValidationClass.js.
  2. Define the Component: Add the following code to FormValidationClass.js to 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 validate method checks if the username field is empty and if the email field contains an @ symbol. It sets error messages if the validations fail.
    • The handleSubmit method 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.
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the FormValidationClass component:
    // App.js
    import React from 'react';
    import FormValidationClass from './FormValidationClass';
    
    function App() {
      return (
        <div>
          <FormValidationClass />
        </div>
      );
    }
    
    export default App;
    
  4. 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

  1. Create a New File for the Component: In the src directory, create a new file named InputValidationFunction.js.
  2. Define the Component: Add the following code to InputValidationFunction.js to 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 useState hook is used to create state variables for username and usernameError.
    • The validate function checks if the username field is empty and sets an error message if it is.
    • The handleSubmit function 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.
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the InputValidationFunction component:
    // App.js
    import React from 'react';
    import InputValidationFunction from './InputValidationFunction';
    
    function App() {
      return (
        <div>
          <InputValidationFunction />
        </div>
      );
    }
    
    export default App;
    
    

`

  1. 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

  1. Create a New File for the Component: In the src directory, create a new file named FormValidationFunction.js.
  2. Define the Component: Add the following code to FormValidationFunction.js to 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 useState hook is used to create state variables for formData and errors.
    • The handleChange function updates the formData state when the input fields change.
    • The validate function checks if the username field is empty and if the email field contains an @ symbol. It sets error messages if the validations fail.
    • The handleSubmit function 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.
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the FormValidationFunction component:
    // App.js
    import React from 'react';
    import FormValidationFunction from './FormValidationFunction';
    
    function App() {
      return (
        <div>
          <FormValidationFunction />
        </div>
      );
    }
    
    export default App;
    
  4. 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

  1. Controlled Components: Forms in React are controlled by state, allowing you to manage the form data and behavior fully.
  2. Error Handling: React makes it easy to display error messages and manage validation logic.
  3. Multiple Form Controls: React supports various form controls, including input fields, checkboxes, radio buttons, and select dropdowns.
  4. useState Hook: The useState hook is essential for managing state in functional components, making it easy to handle form data and validation.
  5. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top