In the dynamic world of web development, forms play a pivotal role in user interactions and data collection. In this blog post, we'll dive into the process of building a form with React.js and explore the art of form validation. By the end of this tutorial, you'll have a solid understanding of how to create a powerful and user-friendly form, complete with client-side validation.

Prerequisites:

To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Familiarity with React.js will be beneficial but not essential, as we'll guide you through each step.



Code of Form Validation using React JS:

import React, { useState } from 'react';
import './App.css'

const FormValidationExample = () => {

  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  })

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

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

  const handleSubmit = (e) => {
    e.preventDefault()
    const validationErrors = {}
    if(!formData.username.trim()) {
        validationErrors.username = "username is required"
    }

    if(!formData.email.trim()) {
        validationErrors.email = "email is required"
    } else if(!/\S+@\S+\.\S+/.test(formData.email)){
        validationErrors.email = "email is not valid"
    }

    if(!formData.password.trim()) {
        validationErrors.password = "password is required"
    } else if(formData.password.length < 6){
        validationErrors.password = "password should be at least 6 char"
    }

    if(formData.confirmPassword !== formData.password) {
        validationErrors.confirmPassword = "password not matched"
    }

    setErrors(validationErrors)

    if(Object.keys(validationErrors).length === 0) {
        alert("Form Submitted successfully")
    }

  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Username:</label>
        <input
          type="text"
          name="username"
          placeholder='username'  
          autoComplete='off'  
          onChange={handleChange}  
        />
          {errors.username && <span>{errors.username}</span>}  
      </div>
      <div>
        <label>Email:</label>
        <input
          type="email"
          name="email"
          placeholder='example@gmail.com'
          autoComplete='off'
          onChange={handleChange}
        />
          {errors.email && <span>{errors.email}</span>}  
      </div>
      <div>
        <label>Password:</label>
        <input
          type="password"
          name="password"
          placeholder='******'
          onChange={handleChange}
        />
          {errors.password && <span>{errors.password}</span>}  
      </div>
      <div>
        <label>Confirm Password:</label>
        <input
          type="password"
          name="confirmPassword"
          placeholder='******'
          onChange={handleChange}
        />
          {errors.confirmPassword && <span>{errors.confirmPassword}</span>}  
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default FormValidationExample;


CSS Code for Form:

/* Styles for the form container */
* {
    box-sizing: border-box;
}
form {
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
 
  /* Styles for the form fields and labels */
  form div {
    margin-bottom: 15px;
  }
 
  label {
    display: block;
    font-weight: bold;
  }
 
  input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
  }
 
  /* Styles for error messages */
  span {
    color: #e74c3c;
    font-size: 14px;
    margin-top: 5px;
    display: block;
  }
 
  /* Styles for the submit button */
  button {
    background-color: #3498db;
    color: #fff;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
 
  button:hover {
    background-color: #2980b9;
  }
 

I hope this post was helpful for you.