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>
);
}
π§ 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)