Blog>
Snippets

Form Validation with Next.js and Yup

Demonstrate how to implement client-side form validation in Next.js using Yup schema validation when a form is submitted.
import React, { useState } from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

// Define Yup schema for form validation
const validationSchema = Yup.object({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Enter a valid email').required('Email is required'),
  password: Yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'),
});

// Form component
const ContactForm = () => {
  // Initialize the formik object
  const formik = useFormik({
    initialValues: { name: '', email: '', password: '' },
    validationSchema,
    onSubmit: values => {
      // handle form submission
      alert(JSON.stringify(values, null, 2));
    }
  });
  
  return (
    <form onSubmit={formik.handleSubmit}>
      <input
        type="text"
        name="name"
        onChange={formik.handleChange}
        value={formik.values.name}
        onBlur={formik.handleBlur}
      />
      {formik.touched.name && formik.errors.name ? <div>{formik.errors.name}</div> : null}

      <input
        type="email"
        name="email"
        onChange={formik.handleChange}
        value={formik.values.email}
        onBlur={formik.handleBlur}
      />
      {formik.touched.email && formik.errors.email ? <div>{formik.errors.email}</div> : null}

      <input
        type="password"
        name="password"
        onChange={formik.handleChange}
        value={formik.values.password}
        onBlur={formik.handleBlur}
      />
      {formik.touched.password && formik.errors.password ? <div>{formik.errors.password}</div> : null}

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

export default ContactForm;
This code uses the useFormik hook from Formik library to handle form state and submission, with Yup for defining the validation schema. The ContactForm component renders a simple form and sets up the validation schema using Yup. Form elements like input are tied to formik's handleChange, and values, and errors are displayed conditionally based on formik's touched and errors state. The form submission is handled by formik's handleSubmit, which will trigger the validation according to the defined schema before running the onSubmit callback.