Back to cookbook

ChatGPT Prompt to Build a Reusable React Form Component with Validation

16 views Published

Make this prompt yours

Share

This ChatGPT prompt generates a reusable React form component with built-in field validation, meant for frontend developers who want a working starting point instead of wiring up form state and error handling from scratch each time. It's suited for common cases like signup forms, contact forms, or settings panels.

The prompt specifies the fields, validation rules, and styling approach up front so the model produces a self-contained component with local state management, inline error messages, and a disabled submit state while the form is invalid — rather than a form that only looks right but skips validation logic entirely.

It's written for React with plain useState, since that runs without extra dependencies, but the constraints section lets you swap in a form library like React Hook Form or Formik, or specify TypeScript, if that matches your codebase.

Prompt template

Make this prompt yours

prompt-template
248 tokens
Role: You are a frontend engineer who writes clean, reusable React components. Context: - Component purpose: [E.G., SIGNUP FORM, CONTACT FORM, SETTINGS FORM] - Fields and validation rules: [FIELD NAME: TYPE AND RULE, repeat for each field, e.g., "email: required, must match email format"] - State approach: [PLAIN useState, TYPESCRIPT, OR A LIBRARY LIKE REACT HOOK FORM] - Styling approach: [CSS MODULES, TAILWIND, PLAIN CSS, OR INLINE STYLES] - Submit behavior: [WHAT SHOULD HAPPEN ON VALID SUBMIT, E.G., "CALL AN onSubmit PROP WITH FORM VALUES"] Constraints: - Component must be self-contained and reusable, accepting props for initial values and onSubmit - Each field must show its own inline error message that clears once the field becomes valid - Submit button must be disabled while any required field is invalid Task: Write the complete React component code implementing the form above. Output format: 1. The full component code in a single fenced code block 2. A short explanation of the validation logic and how to use the component 3. Any assumptions made about props or styling

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
84 tokens
Component purpose: Newsletter signup form Fields and validation rules: name: required, minimum 2 characters; email: required, must match a standard email format State approach: plain useState, JavaScript (no TypeScript) Styling approach: plain CSS with a "form-field" and "form-error" class Submit behavior: call an onSubmit prop with { name, email } when the form is valid

When to use it

  • Scaffolding a new signup, login, or contact form for a React project
  • Adding client-side validation to a form that currently submits without checks
  • Prototyping a settings or profile-edit form before wiring it to a real API
  • Generating a starting component to adapt to your team's existing form library

Best practices

  • List every field with its exact validation rule instead of saying "validate the form"
  • Specify whether you're using plain React state, TypeScript, or a form library like Formik
  • Ask for inline error messages tied to each field, not just a generic form-level error
  • Request that the submit button stay disabled until all required fields pass validation

Common mistakes

  • Not specifying validation rules, which produces a form with only required-field checks
  • Leaving out the styling approach, so the model guesses between CSS modules, Tailwind, or inline styles
  • Accepting the first draft without checking that error messages clear once a field is fixed
  • Asking for "a form" instead of specifying controlled vs. uncontrolled inputs, which affects how state is wired

FAQs

How do I get ChatGPT to generate React form validation, not just the UI?

List each field's exact validation rule in the prompt (required, format, min length) instead of a general instruction to "validate the form," so the model writes real validation logic.

Can this prompt generate a TypeScript version instead?

Yes, change the state approach line to specify TypeScript and the model will add prop and state types, though you should still review the generated types against your project's conventions.

Should I use this for a form library like Formik or React Hook Form instead of plain useState?

Specify the library in the state approach section and the model will use its API instead of plain useState; plain state is simplest when you don't want an extra dependency.

Why does the submit button start disabled?

The prompt requires the button to stay disabled until every required field passes validation, which prevents submitting incomplete or invalid data by mistake.

Found this prompt useful? Share it.

Share

More in React Prompt Recipes

React Prompt Recipes

AI Prompt to Build a React Kanban Board With Drag-and-Drop

This prompt gives ChatGPT, Claude, or Gemini a complete specification for building a React Kanban board with drag and drop column reordering…

You are a senior React developer specializing in accessible, production-ready UI components.

Context:
- Framework: [REACT VERSION, e.g. React 18 with TypeScript]
- Drag-and-drop library: [LIBRARY NAME, e.g. @dnd-kit/core]
- Styling approach: [e.g. Tailwind CSS, CSS Modules, styled-components]
- Columns or workflow stages: [LIST OF COLUMN NAMES, e.g. Backlog, In Progress, Review, Done]
- State source: [e.g. local state, Zustand store, REST API endpoint]

Build a Kanban board component with the following requirements:
1. Render one column per workflow stage listed above, each showing its card count
2. Support dragging cards between columns and reordering cards within a column
3. Support keyboard-based reordering, not mouse-only interaction, for accessibility
4. Identify cards by a stable [ID FIELD NAME] field, never by array index
5. Call a [CALLBACK NAME] function on every successful move, passing the card id, source column, destination column, and new index
6. Show an optimistic UI update immediately, then roll back if [CALLBACK NAME] rejects
7. Handle empty columns and drops outside any valid column gracefully

Output format:
- The main board component
- Column and Card subcomponents
- Any custom hooks used for drag state
- A short usage example showing how to wire [CALLBACK NAME] to a real API call
- Brief notes on any library-specific setup required, such as providers, context, or CSS imports

Make this prompt yours

React Prompt Recipes

AI Prompt for an Accessible React Autocomplete Combobox

This prompt is for developers asking Claude , ChatGPT , or Gemini to generate a React autocomplete combobox component, the input plus dropdo…

Generate a React component with the following specification.

ROLE
- You are a frontend engineer who writes accessible, production-ready React components.

COMPONENT
- A searchable autocomplete combobox named [COMPONENT NAME].
- Props: options ([OPTION SHAPE, e.g. array of {id, label}]), value, onChange, placeholder.
- Controlled component: value and onChange are provided by the parent; do not manage selected value as internal-only state.

ACCESSIBILITY REQUIREMENTS
- Use the ARIA 1.2 combobox pattern: role="combobox" on the input, role="listbox" on the options container, role="option" on each item, and aria-activedescendant to track the highlighted option.
- Support keyboard interaction: ArrowDown/ArrowUp to move highlight, Enter to select the highlighted option, Escape to close the list, Home/End to jump to first/last option.
- Announce the number of matching results to screen readers when the list updates.

BEHAVIOR
- Filter options client-side, debounced by [DEBOUNCE MS, e.g. 150]ms.
- Close the dropdown on click outside or on Escape.
- If no options match, display [EMPTY STATE MESSAGE] inside the listbox instead of hiding it.

OUTPUT FORMAT
- A single functional component using hooks, written in [TYPESCRIPT OR JAVASCRIPT], with inline comments marking each accessibility feature.

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Command Palette (Cmd+K) Component

This AI prompt generates a complete React command palette component, the kind of Cmd+K (or Ctrl+K) search and action overlay popularized by…

ROLE: You are a senior frontend engineer who writes accessible, reusable React components with TypeScript.

TASK: Build a command palette (Cmd+K / Ctrl+K) component for a React application with the following behavior:
1. A global keyboard shortcut ([SHORTCUT, E.G. CMD+K]) opens the palette from anywhere in the app.
2. The palette renders as a centered modal overlay with a search input focused automatically on open.
3. Below the input, show a filtered, scrollable list of commands based on a prop-driven array of {id, label, icon, action, group} items.
4. Support fuzzy or substring matching on the label as the user types, updating the list in real time.
5. Support arrow-up/arrow-down to move the active selection and Enter to run the selected command's action and close the palette.
6. Escape closes the palette and returns focus to whatever element triggered it.
7. Group commands by their 'group' field with a small header label per group in the results list.

CONSTRAINTS:
- Use React hooks only, no class components.
- Trap focus inside the palette while it is open.
- Use ARIA roles appropriate for a combobox/listbox pattern.
- Style with [STYLING APPROACH, E.G. TAILWIND CSS / CSS MODULES].

OUTPUT FORMAT: A single CommandPalette.tsx component file plus a short usage example showing how to pass the command list and mount the component, with brief inline comments explaining the keyboard and focus logic.

APP CONTEXT: [BRIEF DESCRIPTION OF THE APP AND EXAMPLE COMMANDS, E.G. 'PROJECT MANAGEMENT TOOL WITH COMMANDS LIKE NEW TASK, GO TO SETTINGS, INVITE TEAMMATE']

Make this prompt yours