DEV Community

Cover image for 🌟 Using Yup with Formik in Next.js πŸ’‘
Himanay Khajuria
Himanay Khajuria

Posted on

🌟 Using Yup with Formik in Next.js πŸ’‘

Hello developers! πŸ‘‹

In this post, you’ll learn how to validate forms in a Next.js project using Formik + Yup. This is a simple step-by-step guide specially written for beginners. Let’s go πŸš€


πŸ’‘ What are Formik and Yup?

πŸ‘‰ Formik β†’ A small library that helps you manage form state, handle submission, and show errors easily in React and Next.js.

πŸ‘‰ Yup β†’ A schema validation library used to check if the data entered by users is valid (like checking email format or if a field is empty).

πŸ’¬ In simple words:

Formik handles the form β†’ Yup checks if the values are correct.

Together they make form validation easy, fast, and clean. ✨


πŸ’­ Why use Formik + Yup?

Without Validation With Formik + Yup
You write a lot of manual code for handling inputs and errors Formik handles form values and errors automatically
Each field needs if checks for validation Yup schema defines all rules in one clean place
Hard to maintain large forms Validation logic stays simple and reusable

πŸ’» Example β†’ Login Form in Next.js

Here’s a simple login form that uses Formik and Yup.

You can paste this directly inside your Next.js app in pages/login.js or app/login/page.jsx.

"use client";
import React from "react";
import { useFormik } from "formik";
import * as Yup from "yup";

export default function LoginPage() {
  // βœ… Step 1: Create validation rules with Yup
  const validationSchema = Yup.object({
    email: Yup.string()
      .trim("Email cannot have spaces at start or end")
      .email("Invalid email format")
      .required("Email is required")
      .matches(
        /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/,
        "Please enter a valid email like demo@domain.com"
      ),
    password: Yup.string()
      .min(5, "Password must be at least 5 characters"),
      .required("Password is required"),
  });

  // βœ… Step 2: Use Formik hook
  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    validationSchema,
    onSubmit: (values) => {
      console.log("Login credentials:", values);
      alert("Login successful πŸŽ‰");
    },
  });

  return (
    <div style={{ maxWidth: 400, margin: "50px auto", fontFamily: "Arial, sans-serif" }}>
      <h1 style={{ textAlign: "center" }}>πŸ” Login</h1>

      <form onSubmit={formik.handleSubmit} noValidate>
        {/* Email Field */}
        <div style={{ marginBottom: 16 }}>
          <label htmlFor="email">Email:</label>
          <input
            id="email"
            name="email"
            type="email"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.email}
            style={{
              width: "100%",
              padding: "8px",
              marginTop: "4px",
              border: "1px solid #ccc",
              borderRadius: "5px",
            }}
            placeholder="Enter your email"
          />
          {formik.touched.email && formik.errors.email && (
            <div style={{ color: "red", fontSize: "13px" }}>
              {formik.errors.email}
            </div>
          )}
        </div>

        {/* Password Field */}
        <div style={{ marginBottom: 16 }}>
          <label htmlFor="password">Password:</label>
          <input
            id="password"
            name="password"
            type="password"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.password}
            style={{
              width: "100%",
              padding: "8px",
              marginTop: "4px",
              border: "1px solid #ccc",
              borderRadius: "5px",
            }}
            placeholder="Enter your password"
          />
          {formik.touched.password && formik.errors.password && (
            <div style={{ color: "red", fontSize: "13px" }}>
              {formik.errors.password}
            </div>
          )}
        </div>

        <button
          type="submit"
          disabled={formik.isSubmitting}
          style={{
            width: "100%",
            backgroundColor: "#0F13B9",
            color: "#fff",
            padding: "10px",
            border: "none",
            borderRadius: "5px",
            cursor: "pointer",
          }}
        >
          {formik.isSubmitting ? "Signing in..." : "Sign In"}
        </button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

🧠 How it works (Step-by-Step)

1️⃣ Import needed packages β†’ useFormik and Yup.

2️⃣ Create a Yup validation schema β†’ defines email and password rules.

3️⃣ Initialize Formik with initial values and the schema.

4️⃣ Add form fields and connect them with Formik’s handlers.

5️⃣ Display validation errors using formik.touched and formik.errors.

6️⃣ On submit β†’ if inputs pass validation β†’ run your logic (like login API).

πŸ’‘ Tip: Formik + Yup saves you from writing long if-else validation checks!


πŸ’¬ Some Tips for Beginners

βœ… Keep one Yup schema per form β†’ easier to manage.

βœ… Use onBlur β†’ shows errors when the user leaves a field.

βœ… Show clear and friendly error messages.

βœ… Use formik.isSubmitting to disable the button while submitting.

βœ… Try adding custom rules in Yup for stronger validation.


✨ Conclusion

Using Formik with Yup in your Next.js project is a smart way to build forms that are clean, easy to maintain and beginner-friendly.

It reduces boilerplate, handles validation smoothly and gives you full control πŸ’»

Keep building, keep experimenting and enjoy coding! πŸš€

Top comments (0)