Form Handling and Validation in Next.js

Building forms and performing data validation are essential parts of web application development. In this section, we will explore how to build forms and conduct data validation in your Next.js application. We'll also delve into popular form libraries like react-hook-form and Formik to efficiently manage form state and perform data validation.

Using react-hook-form for Form Handling

react-hook-form is a library that simplifies managing form state and conducting data validation in your Next.js application. Below is an example of how to use react-hook-form to build a registration form:

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

function RegistrationForm() {
  const { register, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        type="text"
        name="username"
        placeholder="Username"
        ref={register({ required: true, minLength: 5 })}
      />
      {errors.username && <p>Username is required and must be at least 5 characters long</p>}

      <input
        type="email"
        name="email"
        placeholder="Email"
        ref={register({ required: true, pattern: /^\S+@\S+$/i })}
      />
      {errors.email && <p>Valid email is required</p>}

      <button type="submit">Register</button>
    </form>
  );
}

export default RegistrationForm;

In the above example, we use react-hook-form to manage form state and perform data validation. The form is submitted when the user clicks the Register button, and validation errors are displayed if any.

Using Formik for Form Handling

Formik is a powerful library for managing form state, data validation, and handling form-related interactions. Here's an example of how to use Formik in your Next.js application:

import { Formik, Form, Field, ErrorMessage } from 'formik';

function ContactForm() {
  const initialValues = {
    name: '',
    email: '',
  };

  const validate = (values) => {
    const errors = {};

    if (!values.name) {
      errors.name = 'Name is required';
    }

    if (!values.email) {
      errors.email = 'Email is required';
    }

    return errors;
  };

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

  return (
    <Formik initialValues={initialValues} validate={validate} onSubmit={onSubmit}>
      <Form>
        <div>
          <Field type="text" name="name" placeholder="Name" />
          <ErrorMessage name="name" component="div" />
        </div>
        <div>
          <Field type="email" name="email" placeholder="Email" />
          <ErrorMessage name="email" component="div" />
        </div>
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
}

export default ContactForm;

In the above example, we use Formik to manage form state and perform data validation. Validation errors are displayed as messages if they occur.

Conclusion

This section has introduced you to building forms and conducting data validation in your Next.js application. You've learned how to use the react-hook-form and Formik libraries to efficiently manage form state and perform data validation. This will help you create interactive forms that provide a better user experience and responsiveness.