How To Validate Form in React: Step-by-Step Guide

  • react-js
  • 89 Views
  • 5 Min Read
  • 9 Jul 2024
Hi, developer! Welcome to this article. We get methods to create React form validation, like formik, yup, react-hook-form, and more. But in this article, we will create a client-side form using the UseState hook, for which we will not need any external libraries. With useState hooks, we can easily manage form status and validation.
 
So, let's jump on this fundamental.
 
 

7 Steps You Should Consider Before Starting Your Project

 
It is important to make a plan to build the form validation project easily. Below, we have given seven steps through which we will create the form.

 

      1. Defining Requirements: Identify the form fields and validation rules.

 

      2. Planning state management: Decide how to manage the form state using useState

 

      3. Designing event handlers: Create functions to update the form state on user input.

 

      4. Implementing validation logic: Write validation rules and update the error state accordingly.

 

      5. Handling form submission: Validate form data and display appropriate messages.

 

      6. Providing user feedback: Show success or error messages to the user.

 

      7. Testing thoroughly: Ensure the form works correctly in various scenarios.

 

 

Understanding Form Validation:

 
Form validation in ReactJS is all about verifying the information users input into an application. It's like having a virtual assistant double check that everything you enter is correct. For instance, your first name can't be empty, and your password can't be blank either.
 
Assume you are creating an account, and the platform wants a strong password. It's not just about selecting any pair of characters; there are rules to follow.
 
  • Passwords must be at least 8 characters long.

 

  • They must include uppercase and lowercase letters.

 

  • At least one digit and special characters are necessary.
 
Including that all of these requirements are met improves security and the user experience. This is when form validation comes in handy.
 
First, we create a simple React JS form, capturing essential details like first name, last name, email, mobile number, password, and confirmation.
 
 

Launching Your React Adventure: Getting Started

 
Begin Your React Adventure: Let's Create a New Project with the Create React App command.
 
npx create-react-app form-validation
 
Let's clean up our project for good practice! In the 'public' folder, remove files like favicon.ico, logos, manifest.json, and robots.txt. Then, head to the 'src' folder and delete App.test.js, index.css, logo.svg, reportWebVitals.js, and setupTests.js. While these files have their advantages, we'll delve into their details in another article. For now, let's keep our project neat and focused.
 
Remove some code from the App.js and Index.js files that we do not need.
 
Now our project should look like this:
 
Form validation
 
After creating your project, create a new file called FormComponent.jsx and FormComponent.css in your project's "src" folder.
 
Creating a Form Component:
 
In the FormComponent.js file, we'll create a functional component named FormComponent. This component will handle the form and manage its state effectively using the useState hook.
 
import React, { useState } from 'react';
import './FormComponent.css';

const FormComponent = () => {
    const [formData, setFormData] = useState({
        firstName: '',
        lastName: '',
        email: '',
        mobileNumber: '',
        password: '',
        confirmPassword: '',
    });
    const [errors, setErrors] = useState({});
    const [submitted, setSubmitted] = useState(false);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value,
        });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const newErrors = {};
        if (!formData.firstName) {
            newErrors.firstName = 'First name is required';
        }
        if (!formData.lastName) {
            newErrors.lastName = 'Last name is required';
        }
        if (!formData.email) {
            newErrors.email = 'Email is required';
        } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
            newErrors.email = 'Email is invalid';
        }
        if (!formData.mobileNumber) {
            newErrors.mobileNumber = 'Mobile number is required';
        } else if (!/^\d{10}$/.test(formData.mobileNumber)) {
            newErrors.mobileNumber = 'Mobile number is invalid';
        }
        if (!formData.password) {
            newErrors.password = 'Password is required';
        } else if (formData.password.length < 8 || !/\d/.test(formData.password) || !/[a-zA-Z]/.test(formData.password)) {
            newErrors.password = 'Password must be at least 8 characters long and contain at least one letter and one digit';
        }
        if (!formData.confirmPassword) {
            newErrors.confirmPassword = 'Confirmation password is required';
        } else if (formData.confirmPassword !== formData.password) {
            newErrors.confirmPassword = 'Passwords do not match';
        }
        setErrors(newErrors);
        if (Object.keys(newErrors).length === 0) {
            console.log(formData);
            setFormData({
                firstName: '',
                lastName: '',
                email: '',
                mobileNumber: '',
                password: '',
                confirmPassword: '',
            });
            setSubmitted(true);
            setTimeout(() => {
                setSubmitted(false);
            }, 3000);
        }
    };

    return (
        <>
            <h1>Form Validation</h1>
            <div className="form-container">
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label>First Name:</label>
                        <input
                            type="text"
                            name="firstName"
                            value={formData.firstName}
                            onChange={handleChange}
                        />
                        {errors.firstName && <span className="error-message">{errors.firstName}</span>}
                    </div>
                    <div className="form-group">
                        <label>Last Name:</label>
                        <input
                            type="text"
                            name="lastName"
                            value={formData.lastName}
                            onChange={handleChange}
                        />
                        {errors.lastName && <span className="error-message">{errors.lastName}</span>}
                    </div>
                    <div className="form-group">
                        <label>Email:</label>
                        <input
                            type="email"
                            name="email"
                            value={formData.email}
                            onChange={handleChange}
                        />
                        {errors.email && <span className="error-message">{errors.email}</span>}
                    </div>
                    <div className="form-group">
                        <label>Mobile Number:</label>
                        <input
                            type="text"
                            name="mobileNumber"
                            value={formData.mobileNumber}
                            onChange={handleChange}
                        />
                        {errors.mobileNumber && <span className="error-message">{errors.mobileNumber}</span>}
                    </div>
                    <div className="form-group">
                        <label>Password:</label>
                        <input
                            type="password"
                            name="password"
                            value={formData.password}
                            onChange={handleChange}
                        />
                        {errors.password && <span className="error-message">{errors.password}</span>}
                    </div>
                    <div className="form-group">
                        <label>Confirm Password:</label>
                        <input
                            type="password"
                            name="confirmPassword"
                            value={formData.confirmPassword}
                            onChange={handleChange}
                        />
                        {errors.confirmPassword && <span className="error-message">{errors.confirmPassword}</span>}
                    </div>
                    <div className="btn">
                        <button type="submit">Submit</button></div>
                    {submitted && <div className="success-message">Form has been submitted</div>}
                </form>
            </div>
        </>
    );
};

export default FormComponent;
 
Form validation UI
 
This component sets up input fields for first name, last name, email, mobile number, password, and confirm password. It uses the useState hook to handle everything related to the form: keeping track of what's entered, dealing with any errors, and letting you know when the form is submitted.
 
I've made the code explanation super easy by breaking it down into 10 simple steps. This will help you understand how everything works smoothly.
 

1. import React, { useState } from 'react'

 
Here, we bring the useState hook from React. The useState helps us handle stateful operations in functional components.
 

2. import './FormComponent.css'

 
This line brings in a CSS file named 'FormComponent.css' that holds styles for our form component. Separating CSS from JavaScript enhances organization and clarity.
 
.form-container {
    width: 25%;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-family: sans-serif;
}

h1 {
    font-family: sans-serif;
    text-align: center;
}

.form-group {
    margin-bottom: 15px;
}

label {
    display: block;
    margin-bottom: 5px;
}

input {
    width: 96%;
    font-size: 16px;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.error-message {
    color: red;
    font-size: 14px;
}

.btn {
    display: flex;
    justify-content: center;
}

button {
    padding: 10px 20px;
    border-radius: 5px;
    border: none;
    color: white;
    background-color: black;
    cursor: pointer;
}

.success-message {
    margin: 0 auto;
    text-align: center;
    font-size: 20px;
    color: green;
    border-radius: 5px;
    padding: 12px;
    margin-bottom: 10px;
}
 

3. const FormComponent = () => {..}

 
Here, we create a functional component called FormComponent using the arrow function. This component manages our form and includes all the form related logic.
 

4. const [formData, setFormData] = useState({..})

 
By using the useState hook, we define a state variable named 'formData'. This variable is like a real-time recorder for our form data. It holds onto important stuff like first name, last name, email, mobile number, password, and confirmation password.
 

5. const [errors, setErrors] = useState({...});

 
We also create a state variable named 'errors' to handle any validation errors linked to form fields. Initially, it's empty but will store error messages as needed.
 

6. const [submitted, setSubmitted] = useState(false);

 
The submitted state variable tracks whether the form has been submitted. It starts as false and is updated to true once the form is successfully submitted.
 

7. const handleChange = (e) => {...}

 
This function is activated whenever an input field changes. It retrieves the name and value of the updated input field from the event object and modifies the formData state accordingly.
 

8. const handleSubmit = (e) => {...}

 
This function is activated when the form is submitted. It stops the default form submission, looks at the form data for errors, updates the error state with any found mistakes, and saves the form data if validation is successful.
 

9. return (...)

 
At the moment, we are beginning to create the JSX for the FormComponent. This JSX defines the form layout, which includes input fields, labels, error warnings, and a submit button.
 

10. {submitted && <div className="success-message">Form has been submitted</div>}

 
This line conditionally renders a success message if the form has been successfully submitted (i.e., the submitted state is true).
 
 

Creating App.js:

 
In App.js, import and use the FormComponent:
 
import FormComponent from './FormComponent'

function App() {
    return (
        <>
            <FormComponent />
        </>
    );
}

export default App;
 
Great job! Let's run the project now. Go ahead and interact with the form to see how the validation behaves in action.
 
 

Conclusion

 
In this guide, we learned how to easily add form validation in React with useState hooks. Just follow the steps and use the example code we provided, so you will be able to easily add form validation to your React projects. Add validation rules and error messages to your project for a better user experience.
 
If you're looking to do form validation using a library, check out this article: Top 4 Libraries for Form Validation in React JS.
 
If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get an answer soon.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....