When building web applications, we use forms to collect inputs from users. Every form field serves a purpose on the application. Forms makes collection of user input like: login details, sign-up information or user feedback easy to collect and analyse.

What is Form Validation?

Form validation is the process of checking if the data entered by a user is correct and complete before sending it to the server
Form validation helps to prevent users from submitting a form with invalid or missing information. For example we can check if:

  • the email typed is correct
  • password is long enough
  • No required field is empty

In this article, I will work you through on how to do basic form validation with reactjs

Getting Started

We will build a simple signup form with three fields:

  • Email
  • Password
  • Username

Step by Step Example

  1. *Basic Setup *

Firstly, we will create a react app with:
npm create vite@latest

follow the prompt as shown below
install vite

choose framework

select a variant
Now run the commands:

cd 
  npm install
  npm run dev

replace formValidation with your project name

Now lets create our signUp Form

//SignUpForm.jsx

import React, { useState } from 'react'

const SignUpForm = () => {
    // use useState to monitor all the input values and error state
    const [userName, setUserName] = useState("")
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")
    const [error, setError] = useState({})


    // submit the form
    const handleSubmit = (e) => {
        e.preventDefault()

        let formErrors = {}

        // validateing the username field
        if(!userName){
            formErrors.userName = "User Name cannot be empty"
        }


        // validateing the email field
        if(!email){
            formErrors.email = "Email is required"
        }else if(!/\S+@\S+\.\S+/.test(email)){
            formErrors.email = "Email is Invalid"
        }

        // validating the password field
        if(!password){
            formErrors.password = "Password is required"
        }else if(password.length < 8){
            formErrors.password = "Password must be at least 8 characters"
        }

        //add the errors
        setError(formErrors)

        // submit if there is no error and reset the input values
        if(Object.keys(formErrors).length === 0) {
            alert("Form submitted successfully")
            setEmail("")
            setPassword("")
            setUserName("")
        }
    }


  return (
    
        Sign Up

        
            Username
             setUserName(e.target.value)}
            />

            {error.userName &&  {error.userName}}
        
        
            Email
             setEmail(e.target.value)}
            />
            {error.email &&  {error.email}}
        
        
            Password
             {setPassword(e.target.value)}}
            />
            {error.password &&  {error.password}}
        

        Submit
    
  )
}

export default SignUpForm
//App.jsx

import './App.css'
import SignUpForm from './signUpForm'

function App() {


  return (
    
      
    
  )
}

export default App

For the CSS

//App.css

* {
    padding: 0;
    margin: 0;
}

.container {
    height: 100vh;
    background-color: gray;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.form-container {
    min-width: 400px;
    background-color: rgb(158, 128, 186);
    padding: 20px;
    border-radius: 10px;
}

h2 {
    font-size: 30px;
    margin-bottom: 30px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
    margin-bottom: 30px;
    position: relative;
}

.error {
    position: absolute;
    bottom: -18px;
    left: 5px;
    color: red;
}


input {
    padding: 10px 20px;
    background-color: gray;
    border: none;
}

label {
    font-size: 20px;
}

button {
    width: 100%;
    padding: 10px;
    background: #000;
    color: white;
}