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:
- Password
 - Username
 
Step by Step Example
- *Basic Setup *
 
Firstly, we will create a react app with:
npm create vite@latest
follow the prompt as shown below

  cd <formValidation>
  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 (
    <form className='form-container' onSubmit={handleSubmit}>
        <h2>Sign Up</h2>
        <div className='form-group'>
            <label htmlFor="">Username</label>
            <input type="text"
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
            />
            {error.userName &&  <p className='error'>{error.userName}</p>}
        </div>
        <div className='form-group'>
            <label htmlFor="">Email</label>
            <input type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
            />
            {error.email &&  <p className='error'>{error.email}</p>}
        </div>
        <div className='form-group'>
            <label htmlFor="">Password</label>
            <input type="password"
                value={password}
                onChange={(e) => {setPassword(e.target.value)}}
            />
            {error.password &&  <p className='error'>{error.password}</p>}
        </div>
        <button>Submit</button>
    </form>
  )
}
export default SignUpForm
//App.jsx
import './App.css'
import SignUpForm from './signUpForm'
function App() {
  return (
    <div className='container'>
      <SignUpForm />
    </div>
  )
}
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;
}


    
Top comments (2)
i dont think its good way to handle , i think instead of implementing like this we can use React hook forms as well and also we have formik for forms .
and yes for validation you can use YUP validation as well .
I appreciate this