React 18 Form Validation with React Hooks Tutorial

Last Updated on by in React JS
In this comprehensive guide, we are going to teach you how to handle form validation in React js using functional component and React hooks.To implement the inline form validation in React we will not use any additional package or third-party module and also show you how to implement regular expression or regex to basic React form validation.

We will create a basic user form with name, email and password after clicking on the submit button, after entering the values in input fields the inline form validation in React form will appear on the React input form fields.

Forms are an essential part of any modern web and mobile applications, forms are used to send direct query to site owners. On top of that form validation prevents bots or fake users from spreading spam.

Before submitting data to the server, we make sure the authenticity of the data from the client side and makes sure that the real data is submitted to the site owners.

In this React client-side form validation example, we will learn with utmost profoundness how to validate a basic and simple form and handle the form validation in React from absolute scratch.

How to Validate Form in React using React Hooks without External Library or Package

Let’s start installing basic React app for creating Form validation in React.

Create React Project

We will install React app using create-react-app.

npx create-react-app react-form-validation

Get inside the project directory.

cd react-form-validation

Install Bootstrap UI framework, and it offers many UI components. We will create user form using Bootstrap 5 in React.

npm install bootstrap --save

Next, import bootstrap.min.css from node_modules in src/App.js file.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Create Functional Component

Create a component in React, create component folder inside the src folder then create UserForm.js file.

Next, paste the following code inside the file.

import React from "react";

function UserForm() {
  return (
    <div>
      <h2>React Simple Form Validation Example</h2>
    </div>
  );
}

export default UserForm;

Next, import the UserForm component in src/App.js file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

import UserForm from "./components/UserForm";

export default function App() {
  return (
    <div className="container mt-5">
      <UserForm />
    </div>
  );
}

Form Validation in React JS using Hooks

To validate the email field, declare the regExp instance outside the React component using the RegExp object and pass the regular expression in the RegExp object.

Next, we are using the formValid object, and this object is checking whether the form state is valid or not based on the isError object.

We defined the name, email, password in functional componenet, set the state along with isError object. This isError object retains the form errors for every state item.

Add the following code in component/UserForm.js file:

import React, { useState } from "react";

const regExp = RegExp(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/);

const formValid = ({ isError, ...rest }) => {
  let isValid = false;

  Object.values(isError).forEach((val) => {
    if (val.length > 0) {
      isValid = false;
    } else {
      isValid = true;
    }
  });

  Object.values(rest).forEach((val) => {
    if (val === null) {
      isValid = false;
    } else {
      isValid = true;
    }
  });

  return isValid;
};

export default function UserForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    isError: {
      name: "",
      email: "",
      password: "",
    },
  });

  const onSubmit = (e) => {
    e.preventDefault();

    if (formValid(formData)) {
      window.alert("Form is invalid!");
    }
  };

  const formValChange = (e) => {
    e.preventDefault();
    const { name, value } = e.target;
    let isError = { ...formData.isError };

    switch (name) {
      case "name":
        isError.name = value.length < 4 ? "Atleast 4 characaters required" : "";
        break;
      case "email":
        isError.email = regExp.test(value) ? "" : "Email address is invalid";
        break;
      case "password":
        isError.password =
          value.length < 6 ? "Atleast 6 characaters required" : "";
        break;
      default:
        break;
    }

    setFormData({
      isError,
      [name]: value,
    });
  };

  const { isError } = formData;

  return (
    <>
      <h2 className="mb-3">React 18 Form Validation On Submit Example</h2>
      <form onSubmit={onSubmit} noValidate>
        <div className="mb-3">
          <label>Name</label>
          <input
            type="text"
            className={
              isError.name.length > 0
                ? "is-invalid form-control"
                : "form-control"
            }
            name="name"
            onChange={formValChange}
          />
          {isError.name.length > 0 && (
            <span className="invalid-feedback">{isError.name}</span>
          )}
        </div>

        <div className="mb-3">
          <label>Email</label>
          <input
            type="email"
            className={
              isError.email.length > 0
                ? "is-invalid form-control"
                : "form-control"
            }
            name="email"
            onChange={formValChange}
          />
          {isError.email.length > 0 && (
            <span className="invalid-feedback">{isError.email}</span>
          )}
        </div>

        <div className="mb-3">
          <label>Password</label>
          <input
            type="password"
            className={
              isError.password.length > 0
                ? "is-invalid form-control"
                : "form-control"
            }
            name="password"
            onChange={formValChange}
          />
          {isError.password.length > 0 && (
            <span className="invalid-feedback">{isError.password}</span>
          )}
        </div>

        <button type="submit" className="btn btn-danger">
          Submit
        </button>
      </form>
    </>
  );
}

We are using the JavaScript switch statement and checking whether the our form state matches the specific condition and returning the error messages.

When the state doesn’t match up with a specific condition. This way we are showing the error messages in React component.

Execute the following code to run the app development server:

npm run start

React form validation

Conclusion

In this tutorial we saw how to validate form data without using any additional package. We had a chance to looked at imperative concepts to implement form validation in React without any Libraries

This is just a basic form validation tutorial in React. Hopefully, we have learned to validate client-side validation with minimum characters, email validation with the regular expression and password validation in React.

I hope you will like this tutorial, please consider it sharing with others.