React Hook Form | React Form Validation | React Hook Form v7 | Tailwind CSS Form React Js

react-hook-form , react js app form validation with react-hook-form using tailwindcss styling
react-hook-form , react js app form validation with react-hook-form using tailwindcss styling

Hi, welcome here in this tutorial we are going to develop a React-Hook-Form validation in React Js App and also use Tailwind CSS styling, The prerequisites for this project are as follows:

  • Node.js should be installed in your system.
  • Create a brand new ReactJs project. Just copy the code below:
				
					code to create React js project:

npx create-react-app my-app

after it run the below command:

cd my-app

after it run the below commands to install Tailwind css into your project:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

after it run the below command to run your react app:

npm start

				
			

The brand-new React Js project should look like this:

brand new react js app
brand new react js app

Here is your code for the App.js file, copy the code below and paste it into your App.js file:

				
					import logo from './logo.svg';
import './App.css';
import FormValidation from './components/FormValidation';

function App() {
  return (
    <div className="App flex justify-center items-center customBG">
      <FormValidation />
    </div>
  );
}

export default App;

				
			

Here is your code for the index.css file, copy the code below and paste it into your index.css file:

				
					@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}

				
			

Here is your code for tailwind.config.js copy the code below and paste it into tailwind.config.js.

				
					/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
				
			

Build a FormValidation.jsx component after it copy the code below and paste it into FormValidation.jsx

				
					import React from 'react'
import { useForm } from 'react-hook-form'

const FormValidation = () => {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();
    const onSubmit = (data) => {
        alert(JSON.stringify(data));
        console.log(watch(data));
    }

    return (
        <>
            <div className='w-96 m-40 text-left'>
                <form className='bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4' onSubmit={handleSubmit(onSubmit)}>
                    <label className='block text-gray-700 text-sm font-bold mt-3 mb-2'>First Name</label>
                    <input className='shadow appearance-none border rounded w-full py-2 px-3 textgray-700 leading-tight focus:outline-none focus:shadow-outline' type="text" id="firstName" placeholder='John'
                        {...register("firstName", {
                            required: true,
                            maxLength: 20,
                            pattern: /^[A-Za-z]+$/i
                        })}

                    />
                    {errors?.firstName?.type === "required" && <p className='text-red-500'>First name is required</p>}
                    {errors?.firstName?.type === "pattern" && (<p className='text-red-500'>Alphabetical characters only</p>)}

                    <label className='block text-gray-700 text-sm font-bold mt-3 mb-2'>Last Name</label>
                    <input className='shadow appearance-none border rounded w-full py-2 px-3 textgray-700 leading-tight focus:outline-none focus:shadow-outline' type="text" id="lastName" placeholder='Doe'
                        {...register("lastName", {
                            pattern: /^[A-Za-z]+$/i
                        })}

                    />
                    {errors?.lastName?.type === "pattern" && (<p className='text-red-500'>Alphabetical characters only</p>)}

                    <label className='block text-gray-700 text-sm font-bold mt-3 mb-2'>Email</label>
                    <input className='shadow appearance-none border rounded w-full py-2 px-3 textgray-700 leading-tight focus:outline-none focus:shadow-outline' type="email" id="email" placeholder='example@gmail.com'
                        {...register("email", {
                            pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
                        })}

                    />
                    {errors?.email?.type === "pattern" && (<p className='text-red-500'>Please write correct email address</p>)}

                    <label className='block text-gray-700 text-sm font-bold mt-3 mb-2'>Password</label>
                    <input className='shadow appearance-none border rounded w-full py-2 px-3 textgray-700 leading-tight focus:outline-none focus:shadow-outline' type="password" id="password" placeholder='********'
                        {...register("password", {
                            minLength: 8,
                            required: true
                        })}

                    />
                    {errors?.password?.type === "minLength" && (<p className='text-red-500'>Your password must be larger then 8 characters</p>)}
                    {errors?.password?.type === "required" && (<p className='text-red-500'>Password is required</p>)}

                    <button type='submit' className='w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline mt-3'>Submit</button>
                </form>
            </div>
        </>
    )
}

export default FormValidation
				
			

After writing the code into the files (don’t forget to save it ,) you can run the command below:

				
					npm start