episyche logo

Episyche

NextJS/Form Validation/

How to add a Form validation in nextjs ?

Published on

How to add a Form validation in nextjs ?
Users give their details in the form application. sometimes they give invalid input and try to jump to the next steps. If we throw an error message they complete the process easily. So, We add form validation.

Introduction :

While developing applications, sometimes we get users' details. so, we use the form application. In this form field, we get some mandatory input fields or password lengths. sometimes the user cannot fill in this field properly. so we alert via an error message.

npm has many libraries for form validation. In this application, we use react hook form because this is one of the best and easy to manipulate.

Form Validation :

Form validation is a “technical process where a web-form checks if the information provided by a user is correct.” The form will either alert the user that they messed up and need to fix something to proceed, or the form will be validated and the user will be able to continue with their registration process.

Next js :

Next.js is a React framework. Next.js is constitutionally an excellent tool to achieve great SEO performance. building super fast static websites that behave dynamically. Next.js when building UI and UX there is flexibility. and the important great community support. To know more about relative links click here

Flow Diagram:


flow diagram

Prerequisites :

  • Next.js

Steps:

Step 1: Installing Library’s

  • If you already have the Next.js project, please copy the project. In this blog, we are using a sample Next.js project code with Tailwind CSS.

  • After creating the Next project install "react-hook-form". using the following command.

1npm i react-hook-form
  • After installing react-hook-form install "hookform/resolvers". using the following command.

1npm i @hookform/resolvers
  • And then install "yup". using the following command.

1npm i yup

Step 2: Update index.js

nextjs_form_validation_example→ pages →index.js

  • Update index.js in the above path

  • For this example, we are using the useForm from react-hook-form, yupResolver from hookform/resolvers/yup, and Yup so we have imported the same here. using the following snippet.

1import { useForm } from "react-hook-form"; 2import { yupResolver } from "@hookform/resolvers/yup"; 3import * as Yup from "yup";

ValidationSchema :

The ValidationSchema ensures that the Response obtained from a request satisfies a set of pre-built rules. and lets you create validation rules for your fields, such as allowed data types, and value ranges.

  • Inside the Home function, add the required error messages for each field. An example ValidationSchema definition is shown in the following snippet.

1 const validationSchema = Yup.object().shape({ 2 first_name: Yup.string().required("First Name is required"), 3 last_name: Yup.string().required("Last name is required"), 4 email: Yup.string().required("Email is required").email("Email is invalid"), 5 password: Yup.string().required("password is required"), 6 }); 7 8 const formOptions = { resolver: yupResolver(validationSchema) }; 9 // get functions to build form with useForm() hook 10 const { register, handleSubmit, formState } = useForm(formOptions); 11 const { errors } = formState
  • Set a function When submitting a form without error, fetch with your URL. using the following snippet.

1 function onSubmit(e) { 2 //Backend API Call operation is handled here. 3 }
  • As shown in the following screenshot.


create validation

Sample code for the /pages/index.js file can be found in the following GitHub URL.

Step 3: Showing an error message

  • Inside the return create a div for showing the error message. and create a button with the type of submit. An example snippet for the same is shown below.

1 <div className="my-8 mx-8"> 2 <form onSubmit={handleSubmit(onSubmit)} id="reset"> 3 <div className="py-1"> 4 <label className="text-gray-600 font-medium" htmlFor="first_name">First Name :</label> 5 <div className="py-2"> 6 <input 7 {...register("first_name")} 8 name="first_name" 9 type="text" 10 className="text-md px-2 text-gray-500 border w-[40rem] focus:outline-none focus:border-orange-500 rounded py-1" 11 id="first_name" 12 /> 13 <div className="text-red-500 ml-2 mt-2">{errors.first_name?.message}</div> 14 </div> 15 </div> 16 <div className="py-1"> 17 <label className="text-gray-600 font-medium" htmlFor="last_name"> 18 Last Name : 19 </label> 20 <div className="py-2"> 21 <input 22 {...register("last_name")} 23 name="last_name" 24 type="text" 25 id="last_name" 26 className="text-md px-2 text-gray-500 border w-[40rem] focus:outline-none focus:border-orange-500 rounded py-1" 27 /> 28 <div className="text-red-500 ml-2 mt-2"> 29 {errors.last_name?.message} 30 </div> 31 </div> 32 </div> 33 <div className="py-1"> 34 <label className="text-gray-600 font-medium" htmlFor="email"> 35 Email : 36 </label> 37 <div className="py-2"> 38 <input 39 {...register("email")} 40 name="email" 41 type="text" 42 id="email" 43 className="text-md px-2 text-gray-500 border w-[40rem] focus:outline-none focus:border-orange-500 rounded py-1" 44 /> 45 <div className="text-red-500 ml-2 mt-2"> 46 {errors.email?.message} 47 </div> 48 </div> 49 </div> 50 <div className="py-1"> 51 <label className="text-gray-600 font-medium" htmlFor="password"> 52 Password : 53 </label> 54 <div className="py-2"> 55 <input 56 {...register("password")} 57 name="password" 58 type="password" 59 id="password" 60 className="text-md px-2 text-gray-500 border w-[40rem] focus:outline-none focus:border-orange-500 rounded py-1" 61 /> 62 <div className="text-red-500 ml-2 mt-2"> 63 {errors.password?.message} 64 </div> 65 </div> 66 </div> 67 <button 68 type="submit" 69 className="border focus:border-1 focus:outline-none focus:border-green-600 px-5 py-1.5 rounded bg-green-500 text-white font-bold hover:bg-green-600" 70 > 71 submit 72 </button> 73 </form> 74 </div>

A Sample Github repo, with all the required configurations, is given below.

Step 4: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL:

1http://localhost:3000/

Result:

  • The Example UI is shown in the following screenshot. and click to submit.


ui of form
  • After submitting the form without entering any data the error message will be shown in the following screenshot.


show error message
  • The email is invalid and also throws an error message. shown in the following screenshot.


  • enter valid field
  • After completing the form without any error submit a form. As shown in the following screenshot.


final out put

Comments