Adding Form Validation in Next.js: A Step-by-Step Guide

Posted by


Adding form validation in Next.js can help ensure data integrity and improve user experience by providing real-time feedback to users when they input incorrect or invalid data. In this tutorial, we will go through the steps to add form validation in a Next.js application using a popular form validation library called Formik.

Step 1: Install Formik and Yup

First, navigate to your Next.js project directory in the terminal and install Formik and Yup by running the following command:

npm install formik yup

Formik is a form management library that simplifies the process of building and handling forms in React applications, while Yup is a schema validation library that allows you to define validation rules for your form fields.

Step 2: Create a Form Component

Next, create a new file called FormComponent.js in the components directory of your Next.js project. In this file, import the necessary dependencies and set up a basic form component using Formik.

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
});

const FormComponent = () => {
  const handleSubmit = (values) => {
    console.log(values);
  };

  return (
    <Formik
      initialValues={{ name: '', email: '' }}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      <Form>
        <div>
          <label htmlFor="name">Name</label>
          <Field type="text" id="name" name="name" />
          <ErrorMessage name="name" component="div" />
        </div>
        <div>
          <label htmlFor="email">Email</label>
          <Field type="email" id="email" name="email" />
          <ErrorMessage name="email" component="div" />
        </div>
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

export default FormComponent;

In this code snippet, we defined a simple form with two input fields for name and email, along with corresponding validation rules using Yup. The validationSchema variable contains the validation rules for the form fields.

Step 3: Render the Form Component

Next, import and render the FormComponent in a page in your Next.js application. For example, create a file called index.js in the pages directory and add the following code:

import FormComponent from '../components/FormComponent';

const Home = () => {
  return (
    <div>
      <h1>Form Validation with Formik and Yup</h1>
      <FormComponent />
    </div>
  );
};

export default Home;

Step 4: Test the Form Validation

Now, run your Next.js application by executing the following command in the terminal:

npm run dev

Navigate to http://localhost:3000 in your web browser to see the form with validation in action. Try submitting the form without filling in the required fields or entering an invalid email to see the validation errors being displayed in real-time.

Congratulations! You have successfully added form validation in your Next.js application using Formik and Yup. You can further customize the validation rules and error messages to suit your application’s requirements and enhance the user experience.