Tutorials Logic, IN info@tutorialslogic.com

React Forms Controlled Components, Validation

What are Forms in React?

A form is any part of the interface where users enter, select, or submit data. Login pages, registration screens, profile editors, contact forms, search bars, newsletter subscriptions, and checkout pages are all forms.

React forms use familiar HTML elements such as input, textarea, select, and button, but React gives you a better way to connect those fields to component state and application logic. That makes it easier to validate data, show custom error messages, enable or disable buttons, display live previews, and submit information without reloading the page.

Forms are one of the most practical parts of React because real applications constantly ask users for information. If you understand form handling well, you can build a large part of day-to-day React interfaces.

Why Form Handling Matters

  • Forms collect data from users
  • Forms often need validation before submission
  • Forms usually contain multiple related fields
  • Forms react to typing, focusing, blurring, selecting, checking, and submitting
  • Good form logic improves both user experience and code maintainability

Controlled and Uncontrolled Forms

In React, forms are usually handled in one of two ways: controlled components and uncontrolled components.

A controlled component gets its current value from React state and updates that state through event handlers. This makes React the single source of truth for the field value.

An uncontrolled component keeps its current value in the DOM, and React reads it only when needed. That can be useful in a few cases, but controlled forms are usually the better default in React applications.

Feature Controlled Component Uncontrolled Component
Where data lives React state The DOM itself
How value is read From state From a ref or the DOM element
Validation Easy to run while the user types Usually checked on submit
Recommended for Most React forms Simple cases and file inputs
Level of control High Lower

Basic Controlled Input

The simplest controlled form example is a text input connected to state. The input displays the state value, and the state updates every time the user types.

This is the foundation of React form handling. Because the value is in state, you can use it anywhere else in the component.

Controlled Text Input

Controlled Text Input
import { useState } from 'react'

function NameForm() {
    const [name, setName] = useState('')

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

            <p>Hello, {name || 'Guest'}</p>
        </div>
    )
}

export default NameForm

Handling Form Submission

When an HTML form is submitted, the browser usually refreshes the page. In React, we normally stop that default behavior by calling event.preventDefault(). This lets us validate the data, send it to an API, show a success message, or update the UI without leaving the page.

Submit a Simple Form

Submit a Simple Form
import { useState } from 'react'

function LoginForm() {
    const [email, setEmail] = useState('')

    const handleSubmit = (e) => {
        e.preventDefault()
        alert(`Submitted email: ${email}`)
    }

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="Email address"
            />
            <button type="submit">Submit</button>
        </form>
    )
}

Working with Multiple Fields

Real forms usually contain more than one field. A common React pattern is to store those related values inside one object and update the correct field by using the input's name attribute.

This approach scales well and keeps related values together in one piece of state.

One State Object for Many Inputs

One State Object for Many Inputs
import { useState } from 'react'

function SignupForm() {
    const [formData, setFormData] = useState({
        firstName: '',
        lastName: '',
        email: ''
    })

    const handleChange = (e) => {
        const { name, value } = e.target

        setFormData((prev) => ({
            ...prev,
            [name]: value
        }))
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log(formData)
    }

    return (
        <form onSubmit={handleSubmit}>
            <input name="firstName" value={formData.firstName} onChange={handleChange} placeholder="First name" />
            <input name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Last name" />
            <input name="email" type="email" value={formData.email} onChange={handleChange} placeholder="Email" />
            <button type="submit">Create Account</button>
        </form>
    )
}

React Form Elements and Their Differences

Most form elements use the same overall pattern, but there are a few important differences to remember.

Control Controlled value Change value
Text, email, password, number value event.target.value
textarea value prop, not child text event.target.value
select value on the select element event.target.value
checkbox checked event.target.checked
radio group checked comparison with one shared name event.target.value
  • A generic change handler can support text fields, textarea, select, radios, and checkboxes when it branches on the control type.
  • Keep numbers as strings while the user is typing when empty and partial values must remain representable; parse at the validation boundary.

All Common Input Types

All Common Input Types
import { useState } from 'react'

function ProfileForm() {
    const [form, setForm] = useState({
        fullName: '',
        bio: '',
        country: 'india',
        gender: 'female',
        subscribe: false
    })

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target

        setForm((prev) => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }))
    }

    return (
        <form>
            <input type="text" name="fullName" value={form.fullName} onChange={handleChange} placeholder="Full name" />
            <textarea name="bio" value={form.bio} onChange={handleChange} rows={4} placeholder="Write a short bio" />
            <select name="country" value={form.country} onChange={handleChange}>
                <option value="india">India</option>
                <option value="usa">United States</option>
                <option value="uk">United Kingdom</option>
            </select>

            <label>
                <input type="radio" name="gender" value="female" checked={form.gender === 'female'} onChange={handleChange} />
                Female
            </label>
            <label>
                <input type="radio" name="gender" value="male" checked={form.gender === 'male'} onChange={handleChange} />
                Male
            </label>
            <label>
                <input type="checkbox" name="subscribe" checked={form.subscribe} onChange={handleChange} />
                Subscribe to updates
            </label>
        </form>
    )
}

React Form Elements and Their Differences - JSX Example

React Form Elements and Their Differences - JSX Example
const handleChange = (e) => {
    const { name, value, type, checked } = e.target

    setForm((prev) => ({
        ...prev,
        [name]: type === 'checkbox' ? checked : value
    }))
}

Showing Live Form Data

Since controlled values are always in state, you can instantly display a preview, compute derived values, or react to user input in real time.

Live Preview Example

Live Preview Example
import { useState } from 'react'

function MessageForm() {
    const [message, setMessage] = useState('')

    return (
        <div>
            <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder="Type your message"
            />

            <h4>Preview</h4>
            <p>{message || 'Your preview will appear here.'}</p>
        </div>
    )
}

Validating Forms in React

Validation means checking that the entered data is acceptable before the form is submitted. For example, you may want to require a name, verify an email format, check password length, or ensure the user agrees to the terms.

Validation can happen in several ways:

This pattern uses two extra pieces of state:

That helps avoid showing every error immediately when the page first loads.

  • While the user types
  • When the field loses focus using onBlur
  • When the user submits the form
  • With a combination of blur and submit for a better experience
  • errors stores validation messages
  • touched tracks which fields the user has interacted with

Validation with Errors and Touched Fields

Validation with Errors and Touched Fields
import { useState } from 'react'

function ValidationForm() {
    const [form, setForm] = useState({ email: '', password: '' })
    const [errors, setErrors] = useState({})
    const [touched, setTouched] = useState({})

    const validate = (values) => {
        const newErrors = {}

        if (!values.email.trim()) newErrors.email = 'Email is required'
        else if (!/\S+@\S+\.\S+/.test(values.email)) newErrors.email = 'Enter a valid email address'

        if (!values.password.trim()) newErrors.password = 'Password is required'
        else if (values.password.length < 8) newErrors.password = 'Password must be at least 8 characters'

        return newErrors
    }

    const handleChange = (e) => {
        const { name, value } = e.target
        const nextForm = { ...form, [name]: value }
        setForm(nextForm)

        if (touched[name]) {
            setErrors(validate(nextForm))
        }
    }

    const handleBlur = (e) => {
        const { name } = e.target
        setTouched((prev) => ({ ...prev, [name]: true }))
        setErrors(validate(form))
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        const allTouched = { email: true, password: true }
        const validationErrors = validate(form)
        setTouched(allTouched)
        setErrors(validationErrors)

        if (Object.keys(validationErrors).length === 0) {
            alert('Form submitted successfully')
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <input type="email" name="email" value={form.email} onChange={handleChange} onBlur={handleBlur} placeholder="Email" />
                {touched.email && errors.email && <p>{errors.email}</p>}
            </div>
            <div>
                <input type="password" name="password" value={form.password} onChange={handleChange} onBlur={handleBlur} placeholder="Password" />
                {touched.password && errors.password && <p>{errors.password}</p>}
            </div>
            <button type="submit">Login</button>
        </form>
    )
}

Validating Forms in React - JSX Example

Validating Forms in React - JSX Example
const validate = (values) => {
    const newErrors = {}

    if (!values.email.trim()) newErrors.email = 'Email is required'
    else if (!/\S+@\S+\.\S+/.test(values.email)) newErrors.email = 'Enter a valid email address'

    if (!values.password.trim()) newErrors.password = 'Password is required'
    else if (values.password.length < 8) newErrors.password = 'Password must be at least 8 characters'

    return newErrors
}

Disabling the Submit Button

Some forms disable the submit button until the entered data looks valid. This improves clarity and reduces unnecessary requests.

Disable Submit Until Form Is Ready

Disable Submit Until Form Is Ready
import { useState } from 'react'

function NewsletterForm() {
    const [email, setEmail] = useState('')
    const isValid = /\S+@\S+\.\S+/.test(email)

    const handleSubmit = (e) => {
        e.preventDefault()
        alert('Subscribed successfully')
    }

    return (
        <form onSubmit={handleSubmit}>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Enter your email" />
            <button type="submit" disabled={!isValid}>Subscribe</button>
        </form>
    )
}

Resetting a Form

After a successful submission, it is common to clear the fields. Controlled forms make this easy because you only need to reset the state back to its initial values.

Reset Form Values

Reset Form Values
import { useState } from 'react'

const initialForm = {
    name: '',
    message: ''
}

function ContactForm() {
    const [form, setForm] = useState(initialForm)

    const handleChange = (e) => {
        const { name, value } = e.target
        setForm((prev) => ({ ...prev, [name]: value }))
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log('Sending form data:', form)
        setForm(initialForm)
    }

    return (
        <form onSubmit={handleSubmit}>
            <input name="name" value={form.name} onChange={handleChange} placeholder="Your name" />
            <textarea name="message" value={form.message} onChange={handleChange} placeholder="Your message" />
            <button type="submit">Send</button>
        </form>
    )
}

Uncontrolled Components with useRef

React also allows uncontrolled fields. In that approach, you do not keep the current value in state. Instead, you read the value from the DOM using a ref.

Uncontrolled fields can work, but they give React less direct control over the current value. That is why controlled components are usually preferred for complex forms.

Uncontrolled Form Example

Uncontrolled Form Example
import { useRef } from 'react'

function SearchForm() {
    const searchRef = useRef(null)

    const handleSubmit = (e) => {
        e.preventDefault()
        alert(`Searching for: ${searchRef.current.value}`)
    }

    return (
        <form onSubmit={handleSubmit}>
            <input ref={searchRef} type="text" placeholder="Search..." />
            <button type="submit">Search</button>
        </form>
    )
}

File Inputs in React

File inputs are a special case. Browsers do not allow JavaScript to fully control the current file value for security reasons, so file inputs are typically handled as uncontrolled elements.

File Input Example

File Input Example
function ResumeUpload() {
    const handleChange = (e) => {
        const file = e.target.files[0]

        if (file) {
            console.log('Selected file:', file.name)
        }
    }

    return (
        <div>
            <label>Upload resume</label>
            <input type="file" onChange={handleChange} />
        </div>
    )
}

A Complete Practical Example

The next example combines several important concepts: multiple fields, one shared change handler, validation, checkbox handling, select handling, submit logic, and form reset behavior. This is much closer to what you would build in a real application.

Complete Registration Form

Complete Registration Form
import { useState } from 'react'

const initialValues = {
    name: '',
    email: '',
    password: '',
    role: 'student',
    agree: false,
    about: ''
}

function RegistrationForm() {
    const [form, setForm] = useState(initialValues)
    const [errors, setErrors] = useState({})
    const [submitted, setSubmitted] = useState(false)

    const validate = (values) => {
        const nextErrors = {}

        if (!values.name.trim()) nextErrors.name = 'Name is required'
        if (!values.email.trim()) nextErrors.email = 'Email is required'
        else if (!/\S+@\S+\.\S+/.test(values.email)) nextErrors.email = 'Enter a valid email address'
        if (!values.password.trim()) nextErrors.password = 'Password is required'
        else if (values.password.length < 8) nextErrors.password = 'Password must be at least 8 characters'
        if (!values.agree) nextErrors.agree = 'You must accept the terms'

        return nextErrors
    }

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target
        setForm((prev) => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }))
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        const validationErrors = validate(form)
        setErrors(validationErrors)

        if (Object.keys(validationErrors).length === 0) {
            console.log('Submitted data:', form)
            setSubmitted(true)
            setForm(initialValues)
        } else {
            setSubmitted(false)
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" name="name" value={form.name} onChange={handleChange} placeholder="Full name" />
            {errors.name && <p>{errors.name}</p>}

            <input type="email" name="email" value={form.email} onChange={handleChange} placeholder="Email" />
            {errors.email && <p>{errors.email}</p>}

            <input type="password" name="password" value={form.password} onChange={handleChange} placeholder="Password" />
            {errors.password && <p>{errors.password}</p>}

            <select name="role" value={form.role} onChange={handleChange}>
                <option value="student">Student</option>
                <option value="developer">Developer</option>
                <option value="designer">Designer</option>
            </select>

            <textarea name="about" value={form.about} onChange={handleChange} placeholder="Tell us about yourself" rows={4} />

            <label>
                <input type="checkbox" name="agree" checked={form.agree} onChange={handleChange} />
                I agree to the terms and conditions
            </label>
            {errors.agree && <p>{errors.agree}</p>}

            <button type="submit">Register</button>
            {submitted && <p>Registration completed successfully.</p>}
        </form>
    )
}

A Complete Practical Example - JSX Example

A Complete Practical Example - JSX Example
const validate = (values) => {
    const nextErrors = {}

    if (!values.name.trim()) nextErrors.name = 'Name is required'
    if (!values.email.trim()) nextErrors.email = 'Email is required'
    else if (!/\S+@\S+\.\S+/.test(values.email)) nextErrors.email = 'Enter a valid email address'
    if (!values.password.trim()) nextErrors.password = 'Password is required'
    else if (values.password.length < 8) nextErrors.password = 'Password must be at least 8 characters'
    if (!values.agree) nextErrors.agree = 'You must accept the terms'

    return nextErrors
}

When useReducer Can Help with Forms

For small and medium forms, useState is usually enough. But when a form becomes large, has many update rules, or contains multiple sections, useReducer can keep the logic easier to understand. Instead of spreading update logic throughout the component, you can dispatch actions such as update_field, set_errors, and reset_form.

Best Practices for React Forms

  • Use controlled components for most form fields
  • Keep the form state shape simple and predictable
  • Use the name attribute to build reusable change handlers
  • Use checked for checkboxes instead of value
  • Call preventDefault() in React submit handlers
  • Show clear validation messages near the related field
  • Reset the form after a successful submission when appropriate
  • Use refs for file inputs and other uncontrolled cases
  • Consider useReducer when form logic becomes too complex

Forms Failure Cases

  • Forgetting to give a controlled input a value
  • Mutating the old form object directly instead of creating a new one
  • Using value instead of checked for a checkbox
  • Forgetting to call preventDefault() on submit
  • Showing every validation error before the user has touched the field
  • Writing too many separate handlers when a shared handler would be simpler

Summary

React forms are based on normal HTML form elements, but React makes them more powerful by connecting field values to state and event handlers. Controlled components are the main pattern because they make validation, conditional UI, previews, submission, and reset logic much easier to manage.

Once you understand controlled inputs, shared change handlers, validation, submit handling, reset patterns, and the role of refs for uncontrolled fields, you can build most real-world React forms confidently.

Before you move on

React Forms Controlled Components, Validation Mastery Check

5 checks
  • A form is any part of the interface where users enter, select, or submit data.
  • Login pages, registration screens, profile editors, contact forms, search bars, newsletter subscriptions, and checkout pages are all forms.
  • React forms use familiar HTML elements such as input, textarea, select, and button, but React gives you a better way to connect those fields to component state and application logic.
  • That makes it easier to validate data, show custom error messages, enable or disable buttons, display live previews, and submit information without reloading the page.
  • Forms are one of the most practical parts of React because real applications constantly ask users for information.

React JS Questions Learners Ask

A controlled input must receive both the current value and an onChange path that writes the next value back into state.

Validation answers "is this value acceptable?" while touched answers "has the user interacted with this field yet?" A required email field is invalid on the first render, but showing an error immediately can make the form feel broken before the user does anything.

A file input is intentionally different because browsers do not allow JavaScript to set its selected files for security reasons. You can read files from event.target.files or a ref, but you should not try to control the file list with a value prop the way you control a text input.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.