View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Create a Sign Up Form in React with Validations?

By Pavan Vadapalli

Updated on Jun 18, 2025 | 14 min read | 11.78K+ views

Share:

Latest Update:

The recent React Router v7.5.x release (v7.5.0 to v7.5.1, April 2025) focuses on better pre-rendering, dependency optimization, and improved error handling, primarily when used with modern build tools like Vite.

A sign up form in React is a fundamental component for user onboarding in modern web applications. It involves managing state, handling user input, validating form fields, and ensuring a smooth user experience. Building a sign up form in React strengthens your understanding of component design and state management. It also lays the foundation for more complex features like authentication and user profile management.

In this blog, we’ll explain how to create a sign up form in ReactJS from scratch, highlight best practices, and walk you through implementing it.

Looking to boost your front-end development skills? Explore upGrad’s Software Engineering courses with real-world projects and expert mentorship to help you master React fundamentals. Enroll now!

Step-by-Step Implementation to Create a Sign Up Form in React with Validations

This project focuses on creating a user sign up form in React that features real-time validation, ensuring users receive immediate feedback as they input their details. The form will collect essential information such as the user's name, email, and password, and will include logic to validate entries before any data is submitted. 

To accomplish this, we’ll use React for handling UI interactions and state, HTML to structure the form elements, CSS to design a clean and user-friendly interface, and JavaScript validation logic to enforce data integrity. 

Want to build user-friendly, validated forms in React? Explore these courses to sharpen your form handling skills and boost your front-end development expertise.

1. Project Setup and Required Tools

Before writing any code, you must set up your development environment to ensure everything runs smoothly. Start by installing Node.js and npm. Node.js allows you to run JavaScript outside the browser, while npm (bundled with Node.js) helps you install and manage packages like create-react-app. Once installed, open your terminal and run the following commands to make sure everything is working:

node -v
npm -v

Next, you should install Visual Studio Code (VS Code). It’s a lightweight and powerful code editor that is highly recommended for React development. It supports helpful extensions like ESLint, Prettier, and React snippets, making writing and maintaining code easier. 

Once that’s done, you can create your React project using Create React App. This tool sets up a new React project with a default structure and all necessary configurations so you don’t have to start from scratch. In your terminal, run the following commands:

npx create-react-app signup-form
cd signup-form

Your environment is fully set up, and you’re ready to start building your sign up form in React.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Build powerful forms with backend support. Take your React sign-up form skills to the next level by learning how to handle submissions server-side. Enroll in the free upGrad’s Node.js for Beginners course today and confidently build full-stack applications.

Also Read: How to Install Specific Version of NPM Package?

2. Creating the Sign Up Form in React’s Structure

In this step, you'll create a form that captures key user details like first name, last name, email, password, and role selection. You'll use React’s useState hooks to manage form inputs and validation state, ensuring the form behaves interactively and responsively. Structuring the component logic cleanly and breaking out the validation checks makes your code more maintainable and scalable. 

This is a foundational part of the app, as it sets up both the UI and the logic needed to handle form input, basic error handling, and submission behavior.

Sample Code:

import './App.css';
import {useState} from "react";
import {validateEmail} from "../src/utils";

const PasswordErrorMessage = () => {
return (
  <p className="FieldError">Password should have at least 8 characters</p>
);
};

function App() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState({
  value: "",
  isTouched: false,
});
const [role, setRole] = useState("role");

const getIsFormValid = () => {
  return (
    firstName &&
    validateEmail(email) &&
    password.value.length >= 8 &&
    role !== "role"
  );
};

const clearForm = () => {
  setFirstName("");
  setLastName("");
  setEmail("");
  setPassword({
    value: "",
    isTouched: false,
  });
  setRole("role");
};

const handleSubmit = (e) => {
  e.preventDefault();
  alert("Account created!");
  clearForm();
};

return (
  <div className="App">
    <form onSubmit={handleSubmit}>
      <fieldset>
        <h2>Sign Up</h2>
        <div className="Field">
          <label>
            First name <sup>*</sup>
          </label>
          <input
            value={firstName}
            onChange={(e) => {
              setFirstName(e.target.value);
            }}
            placeholder="First name"
          />
        </div>
        <div className="Field">
          <label>Last name</label>
          <input
            value={lastName}
            onChange={(e) => {
              setLastName(e.target.value);
            }}
            placeholder="Last name"
          />
        </div>
        <div className="Field">
          <label>
            Email address <sup>*</sup>
          </label>
          <input
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
            }}
            placeholder="Email address"
          />
        </div>
        <div className="Field">
          <label>
            Password <sup>*</sup>
          </label>
          <input
            value={password.value}
            type="password"
            onChange={(e) => {
              setPassword({ ...password, value: e.target.value });
            }}
            onBlur={() => {
              setPassword({ ...password, isTouched: true });
            }}
            placeholder="Password"
          />
          {password.isTouched && password.value.length < 8 ? (
            <PasswordErrorMessage />
          ) : null}
        </div>
        <div className="Field">
          <label>
            Role <sup>*</sup>
          </label>
          <select value={role} onChange={(e) => setRole(e.target.value)}>
            <option value="role">Role</option>
            <option value="individual">Individual</option>
            <option value="business">Business</option>
          </select>
        </div>
        <button type="submit" disabled={!getIsFormValid()}>
          Create account
        </button>
      </fieldset>
    </form>
  </div>
);
}

export default App; 

Code Explanation:

  • Password Input State: The password field is a special case where you manage its state using an object instead of a simple string. This object contains two properties: value (the actual password) and isTouched (a boolean that tracks whether the user has interacted with the field). Since you're updating an object, you must use the spread operator when calling the state setter. This ensures that updating one property doesn't unintentionally overwrite the other.
     
  • Password Field Type: The input is set to type="password" so that the characters entered are hidden by default. This is a best practice for any password field to protect user data and enhance trust.
     
  • Tracking User Interaction: To determine if a user has interacted with the password field, you use the onBlur event. This event fires when the input loses focus, meaning the user clicked or tabbed out of it. At that point, you update the isTouched property to true, which allows you to display a helpful validation message only after interaction. This avoids showing premature errors and creates a smoother user experience.
     
  • Form Validation Logic: The getIsFormValid function checks whether all input fields meet the defined criteria. If the function returns true, the form is considered valid and the submit button is enabled. Otherwise, the button remains disabled. The validation rules are as follows:
    • The first name field must not be empty.
    • The email must be non-empty and pass the validateEmail function, which checks for correct formatting.
    • The password must be at least 8 characters long.
    • The user must select a role other than the default "role" placeholder.

Output:

This validation setup helps ensure that only complete and accurate form data can be submitted, reducing errors and improving data quality.

Build dynamic UIs with confidence. Take the next step after learning JavaScript. The upGrad’s React JS for beginners course will teach you to build reusable components and create a real-world Phone Directory app. Ideal for anyone starting their journey in front-end development.

Also read: Top 8 React JS Free Courses with Certificate Options [2025]

Sign Up Form in React Validation Using JavaScript

To make your registration form in React robust and user-friendly, you must ensure the data entered is valid before submission. This helps prevent errors, reduces incorrect data, and improves the overall experience. In this implementation, we separate the email validation logic into a utility file (utils.js) for modularity and reuse. Meanwhile, getIsFormValid and clearForm are defined within the main App.js file to manage form behavior and reset state after submission.

While you can write all validation logic directly inside the component, splitting it into utility functions (like for validating email) keeps your codebase clean, scalable, and easier to maintain.

Creating a Utility File for Email Validation

Moving reusable functions into separate utility files is a good practice to keep your code clean and modular. In this case, you can create a utility function for validating email formats using a regular expression. This function can then be imported wherever needed, such as in form components like App.js.

Sample Code:

// utils.js

export const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

Code Explanation: 

  • utils.js: A new utility file placed inside your src folder.
  • validateEmail Function: Accepts an email string, converts it to lowercase, and uses a regular expression to check for a valid email format.
  • Modular Design: Separating the logic into a utility file promotes reusability and cleaner code, making it easy to use the function across multiple components or forms.

Output:

Also Read: Email Validation in JavaScript: Techniques, Implementation, and Best Practices

Handling Form Validation and Reset in App JS

Inside your main App.js file, you define three important functions:

1. getIsFormValid: This function checks whether the form meets all the required validation rules. It returns true only if:

  • The first name is not empty.
  • The email passes the validateEmail check.
  • The password has at least 8 characters.
  • The user has selected a role other than the default "role" option.

Sample Code:

const getIsFormValid = () => {
  return (
    firstName &&
    validateEmail(email) &&
    password.value.length >= 8 &&
    role !== "role"
  );
};

This function helps control the submit button's disabled state, ensuring that users can only submit valid data.

Output:

2. clearForm: After a successful form submission, you want to return all form fields to their initial states. That’s exactly what this function does:

Sample Code:

const clearForm = () => {
  setFirstName("");
  setLastName("");
  setEmail("");
  setPassword({
    value: "",
    isTouched: false,
  });
  setRole("role");
};

This ensures your form is fresh and ready for another input once the current submission is complete.

3. handleSubmit: When the user clicks the submit button, the handleSubmit function is executed. This function first prevents the default browser behavior of refreshing the page on form submission using e.preventDefault(). Then, it displays an alert message saying "Account created!" to confirm the submission. Immediately after that, it calls the clearForm() function, which resets all form fields to their initial state, clearing the form for a new input.

Sample Code:

const handleSubmit = (e) => {
  e.preventDefault();
  alert("Account created!");
  clearForm();
};

Explore the language behind React. Before building dynamic forms, get confident with JavaScript, the core of all modern web apps. Enroll in the upGrad’s JavaScript Basics from Scratch course and create interactive websites from the ground up.

Also Read: React Functional Components with Examples [In-Depth Guide]

Styling the Sign Up Form in React with CSS

To ensure your sign up form in react works well and looks clean and professional, you style it using CSS. In this example, all styles are written in the App.css file, which is imported into the App.js file. These styles aim to center the form on the page, ensure a clear visual hierarchy, and make the form accessible and responsive.

Sample Code:

.App {
display: flex;
flex: 1;
height: 100vh;
justify-content: center;
align-items: center;
}

fieldset {
display: flex;
width: 480px;
padding: 16px;
border: 1px solid #ccc;
border-radius: 4px;
flex-direction: column;
}

label {
margin-bottom: 8px;
font-size: 14px;
}

sup {
color: red;
top: -2px;
font-size: 95%;
line-height: 0;
position: relative;
vertical-align: baseline;
}

input,
select {
border-radius: 4px;
border: 1px solid #ccc;
height: 32px;
padding: 0 8px;
}

.Field {
position: relative;
padding-bottom: 24px;
display: flex;
flex-direction: column;
}

.FieldError {
position: absolute;
bottom: -6px;
color: red;
font-size: 12px;
}

.Row {
display: flex;
flex-direction: row;
}

button {
padding: 12px;
width: 240px;
border-radius: 4px;
border: 1px solid #ccc;
background-color: darkblue;
color: white;
text-transform: uppercase;
font-size: 14px;

cursor: pointer;
}

button:disabled,
button[disabled] {
border: 1px solid #999999;
background-color: #cccccc;
color: #666666;
cursor: not-allowed;
}

Code Explanation: We use flexbox for layout alignment, apply consistent spacing and padding, style form inputs and buttons for usability, and include error message styles to make validation feedback noticeable.

Output:

Now that you've built a functional sign up form in React, let’s explore some best practices for making it more efficient, scalable, and user-friendly.

Best Practices for Creating a Sign Up Form in React

Best practices help ensure your form is scalable, accessible, user-friendly, and maintainable. Whether using plain React or a form library, the following tips and resources will improve your development workflow and user experience.

Failing to follow best practices can lead to hard-to-maintain code, inconsistent behavior across browsers, poor accessibility for users with disabilities, and frustrating form errors that hurt usability and trust. In production apps, this can directly impact user retention and increase support issues. Here are some best practices to follow:

  • Use Controlled Components: Maintain the form’s state inside React using controlled inputs. This allows real-time validation, dynamic error messages, and form behavior customization.
  • Avoid Overly Complex State Logic: If the form becomes more complex, consider splitting the state into smaller parts or using custom hooks for form logic to maintain clean code separation.
  • Use Semantic HTML and Accessible Labels: Always use <label> tags with htmlFor attributes matching input ids. This boosts accessibility, especially for screen readers.
  • Prevent Unnecessary Renders: Optimize rendering using memoization (React.memouseCallback, etc.) for components that don’t change frequently.
  • Disable Submit Until Valid: Keep the submit button disabled unless all required validations pass, giving users clear feedback and preventing incomplete submissions.
  • Show Real-Time Feedback: Validate fields on blur or input change, and guide the user with helpful error messages so that the user doesn’t wait until submission.
  • Sanitize and Format Inputs: Always sanitize user input and format data (like trimming whitespace from names) before saving or submitting.

Also Read: React useCallback Hook: Why, When & How to Use It?

Let’s see how some popular tools and libraries can enhance your sign up form in React by simplifying state management, validation, and user experience.

Recommended Tools & Libraries to Enhance the Sign Up Form in React

Using the right tools and references when building forms in React can significantly improve your development speed, code quality, and user experience. Whether you're working with vanilla React or using libraries for validation and state management, the following resources are highly recommended for beginners and advanced developers.

Here are some of the recommended tools and libraries to explore:

  • React Official Documentation Forms: Offers foundational knowledge on how React handles forms. It includes examples of elements like <textarea><select>, and file uploads, and explains concepts such as controlled components and handling multiple inputs using event.target.name.
     
  • Formik: One of the most popular open-source form libraries for React. Formik reduces boilerplate, manages form state, validation, and error handling in a clean and structured way. It is Ideal for handling large or complex forms.
     
  • Yup (Validation Schema for Formik): A powerful validation library that integrates seamlessly with Formik. It lets you define schema-based validation rules declaratively, making the validation logic clean and reusable.
     
  • React Hook Form: A performant, lightweight alternative to Formik that uses React hooks to manage form state and validation. It’s known for reducing re-renders and offering better performance in large forms. It is great for performance-sensitive applications.

Take your JavaScript skills to the next level. Deepen your understanding of scopes, prototypes, async programming, and more. Enroll in the free Advanced JavaScript for All course today and build faster, smarter, and more powerful web applications.

Let’s see how you can strengthen your frontend skills with upGrad’s expert-led learning approach.

How can upGrad help you build React Skills?

Creating a Registration form in React with validations is a hands-on way to understand component structure, state management, event handling, and form validation logic in modern web applications. Combining React’s declarative approach with modular JavaScript and clean CSS allows you to build responsive, user-friendly forms that ensure data integrity and elevate the user experience.

Building these foundational skills through guided projects is essential for becoming a confident front-end developer. upGrad’s industry-aligned software development programs offer practical, mentor-led learning that helps you create real-world applications from the ground up.

Explore our additional curated courses to take the next step in your React development journey and gain the skills to build robust, interactive, and scalable user interfaces.

Not sure how concepts like creating sign up form in React, validation, and component logic apply to real-world product development? Connect with upGrad’s expert counselors or drop by your nearest upGrad offline center to discover a personalized learning path aligned with your goals.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

References:
https://ui.dev/react-router-tutorial    
https://reactrouter.com/

Frequently Asked Questions (FAQs)

1. How do I show dynamic validation messages only after a user has interacted with a field?

2. What’s the best way to structure my form components for reusability?

3. How can I handle async validation (e.g., checking if an email is registered)?

4. I need my sign up form in React to work well on mobile devices. What are the best practices for responsive design in React?

5. How do I prevent my form from submitting when validation fails?

6. Should I store form data in local or global states like Redux?

7. How can I securely handle passwords and prevent exposing sensitive data in the UI?

8. My form keeps resetting on re-render. What could be causing this?

9. How do I handle multiple input fields efficiently without writing tons of boilerplate?

10. How do I add conditional logic, such as showing extra fields based on user input (e.g., role selection)?

11. Is it better to write custom validation functions or use a library like Yup?

Pavan Vadapalli

900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks