Forms

Learn how to collect, manage, submit, and validate user input in React forms.

Forms and Form Validation in React

Forms are one of the most common parts of any web application. Whenever you create an account, log in, search for a product, or send a message through a contact page, you are using a form.

In React, forms allow users to enter information, while form validation ensures that the entered data is correct before it is processed or sent to a server.

Learning how to build forms and validate user input is an essential skill for every React developer.

What is a Form?

A form is a section of a webpage that collects information from users.

Common form fields include:

  • Name
  • Email
  • Password
  • Phone Number
  • Address
  • Search Box
  • Comments

Forms make websites interactive by allowing users to provide input.

Real-World Example

Think about creating an account on an online shopping website. Before your account is created, you usually enter:

  • Your name
  • Email address
  • Password
  • Phone number

The website checks whether the information is correct before saving it. This checking process is called form validation.

What is Form Validation?

Form validation is the process of checking whether the information entered by the user is correct and complete.

Validation helps prevent incorrect or incomplete data from being submitted.

Examples include:

  • Required fields must not be empty.
  • Email addresses should follow the correct format.
  • Passwords should meet minimum length requirements.
  • Phone numbers should contain only valid digits.

Validation improves both user experience and data quality.

Managing Form Data with useState

In React, form values are usually stored using the useState Hook.

javascript
import { useState } from "react";

function LoginForm() {
  const [name, setName] = useState("");

  return (
    <input
      type="text"
      value={name}
      onChange={(event) => setName(event.target.value)}
      placeholder="Enter your name"
    />
  );
}

Explanation

  • name stores the current value of the input field.
  • setName() updates the value whenever the user types.
  • value keeps the input field connected to the React state.

This is called a controlled component, where React controls the input value.

Handling Form Submission

When a form is submitted, React usually handles the submission with the onSubmit event.

javascript
function LoginForm() {
  function handleSubmit(event) {
    event.preventDefault();
    alert("Form Submitted!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">
        Submit
      </button>
    </form>
  );
}

Explanation

  • onSubmit runs when the form is submitted.
  • event.preventDefault() prevents the browser from reloading the page.
  • You can then validate or send the form data.

Simple Form Validation

Here is a basic example that checks whether a name has been entered.

javascript
import { useState } from "react";

function App() {
  const [name, setName] = useState("");

  function handleSubmit(event) {
    event.preventDefault();

    if (name === "") {
      alert("Name is required.");
    } else {
      alert("Form Submitted Successfully!");
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      <button type="submit">
        Submit
      </button>
    </form>
  );
}

This example prevents users from submitting an empty form.

Validating an Email Address

You can also validate an email field.

javascript
if (!email.includes("@")) {
  alert("Please enter a valid email address.");
}

This simple check ensures that the email contains the @ symbol. In real-world applications, more advanced validation is often used.

Common Types of Validation

React forms commonly validate:

  • Required fields
  • Email format
  • Password length
  • Confirm password matching
  • Phone number format
  • Minimum and maximum values
  • File uploads
  • Checkbox selection

Different applications may require different validation rules.

Controlled Components

Most React forms use controlled components.

A controlled component means:

  • React stores the input value in state.
  • The input field always displays the value stored in state.
  • Every change updates the state automatically.

This approach keeps the user interface and data synchronized.

Real-World Example

Imagine you are building a login page. The form contains:

  • Email
  • Password
  • Login button

Before allowing the user to log in, React checks:

  • Are both fields filled in?
  • Is the email valid?
  • Is the password long enough?

If everything is correct, the login request is sent. Otherwise, helpful error messages guide the user to fix the input. This improves security and user experience.

Best Practices

When creating React forms:

  • Use useState to manage form values.
  • Use controlled components for better control.
  • Validate data before submitting.
  • Display clear and helpful error messages.
  • Keep forms simple and easy to use.
  • Prevent empty or invalid submissions.
  • Group related fields together for better readability.

Following these practices results in forms that are reliable and user-friendly.

Summary

Forms are an important part of almost every React application because they allow users to enter and submit information. React uses the useState Hook to manage form data and event handlers such as onChange and onSubmit to respond to user actions.

Form validation ensures that users provide correct and complete information before the data is processed. By combining controlled components with proper validation, you can create forms that are easy to use, reliable, and secure.

Key Takeaways

  • Forms collect information from users.
  • React commonly manages form data using the useState Hook.
  • Controlled components keep form inputs synchronized with React state.
  • The onChange event updates form values as users type.
  • The onSubmit event handles form submission.
  • Use event.preventDefault() to stop the page from reloading during form submission.
  • Form validation checks that user input is correct before processing.
  • Well-designed forms improve both the user experience and the quality of collected data.
Let's learn with DevBrainBox AI