Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How To Implement NextJS Form Validation With Formik And Zod ?
Next article icon

How to Add Form Validation In Next.js ?

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. Ne­xt.js, a versatile framework for building Re­act applications, offers form validation that helps verify use­r input against predefined crite­ria, provides immediate feedback, and enhances data quality. In this article, we will cover essential concepts such as required fields, data format validation, and custom e­rror messaging.

Prerequisites:

  • Introduction To Next.js
  • Next.js Components
  • React useState
  • NPM and NPX

Approach

To add form validation in next js app we are going to use useState and use­Effect hooks to dynamically manage form state and validation rule­s.

  • React's useState() hook encapsulates local state variables in functional components. It is a special function that takes the initial state as an argument and returns a two-entry array. It only contains singular values and necessitates useState calls for multiple state implementations.
  • React's useEffect hook handles side effects such as fetching data and updating the DOM, and it runs on every render and makes use of dependency arrays.

Steps to Create the NextJS Application

Step 1: Create a new Next.js project using the following command

  • NPX: Package runner tool in npm 5.2+, npx, is an easy CLI for running Node packages.
npx create-next-app form-validation-app

Step 2: Change to the project directory:

cd form-validation-app

Project Structure:


Next-js-Project-Structure

Example: This example demonstrates form handling in next.js using the react hooks.

JavaScript
// Filename - App.js file   import React, { useState, useEffect } from 'react';  const App = () => {     const [name, setName] = useState('');     const [email, setEmail] = useState('');     const [password, setPassword] = useState('');     const [errors, setErrors] = useState({});     const [isFormValid, setIsFormValid] = useState(false);      useEffect(() => {         validateForm();     }, [name, email, password]);     // Validate form     const validateForm = () => {         let errors = {};          if (!name) {             errors.name = 'Name is required.';         }          if (!email) {             errors.email = 'Email is required.';         } else if (!/\S+@\S+\.\S+/.test(email)) {             errors.email = 'Email is invalid.';         }          if (!password) {             errors.password = 'Password is required.';         } else if (password.length < 6) {             errors.password = 'Password must be at least 6 characters.';         }          setErrors(errors);         setIsFormValid(Object.keys(errors).length === 0);     };     // Submit     const handleSubmit = () => {         if (isFormValid) {             console.log('Form submitted successfully!');         } else {             console.log('Form has errors. Please correct them.');         }     };      return (         <div style={styles.container}>             <div style={styles.form}>                 <h1 style={styles.heading}>                     Geeksforgeeks || Form Validation In Next.js                 </h1>                 <h3 style={styles.subHeading}>Login Page</h3>                 <input                     style={styles.input}                     placeholder="Name"                     value={name}                     onChange={(e) => setName(e.target.value)}                 />                 {errors.name && <p style={styles.error}>{errors.name}</p>}                 <input                     style={styles.input}                     placeholder="Email"                     value={email}                     onChange={(e) => setEmail(e.target.value)}                 />                 {errors.email && <p style={styles.error}>{errors.email}</p>}                 <input                     style={styles.input}                     placeholder="Password"                     value={password}                     onChange={(e) => setPassword(e.target.value)}                     type="password"                 />                 {errors.password && <p style={styles.error}>{errors.password}</p>}                 <button                     style={{ ...styles.button, opacity: isFormValid ? 1 : 0.5 }}                     disabled={!isFormValid}                     onClick={handleSubmit}                 >                     Submit                 </button>             </div>         </div>     ); };  const styles = {     container: {         display: 'flex',         alignItems: 'center',         justifyContent: 'center',         minHeight: '100vh',         backgroundColor: '#f0f0f0',     },     heading: {         fontWeight: 'bold',         fontSize: '25px',         color: "green",         textAlign: "center",     },     subHeading: {         fontWeight: 'bold',         fontSize: '25px',         textAlign: "center",      },     form: {         backgroundColor: '#fff',         padding: '20px',         borderRadius: '8px',         boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',         width: '100%',         maxWidth: '400px',         margin: '0 auto',     },     input: {         width: '100%',         padding: '12px',         marginBottom: '12px',         border: '1px solid #ccc',         borderRadius: '10px',         fontSize: '16px',         transition: 'border-color 0.2s ease',     },     button: {         backgroundColor: 'green',         color: '#fff',         fontWeight: 'bold',         fontSize: '16px',         padding: '12px',         border: 'none',         borderRadius: '10px',         cursor: 'pointer',         width: '40%',         transition: 'opacity 0.2s ease',     },     error: {         color: 'red',         fontSize: '14px',         marginBottom: '6px',     }, };  export default App; 

Step to run the application: Run the Next.js application at URL http://localhost:3000 using the below command.

npm run dev

Output:



Next Article
How To Implement NextJS Form Validation With Formik And Zod ?
author
saurabhkumarsharma05
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Next.js
  • Next.js - Questions

Similar Reads

  • How to perform form validation in React?
    Form validation in React involves ensuring that the data entered into a form meets certain criteria before submission. In this, we will see the form validation in React. Pre-requisitesNodeJS and NPMReactJSReact useState hookHTML, CSS, and JavaScriptSteps to Create React Application And Installing Mo
    4 min read
  • How to Implement Form Validation in React Native ?
    React Native is a JavaScript framework for cross-platform mobile app development. Expo CLI simplifies React Native development with a streamlined process and helpful tools. In this article, we'll see how to implement form validation in react native. Form validation ensures the validity of user input
    4 min read
  • How to add TypeScript in Next.js ?
    In this article, we will learn how to add TypeScript in Next.js. Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in
    5 min read
  • How to add Testimonials in Next.js ?
    In this article, we are going to learn how we can add the Testimonials in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components con
    2 min read
  • How To Implement NextJS Form Validation With Formik And Zod ?
    Form validation is a critical aspect of web development to ensure that user input meets specific criteria before submitting data to the server. Implementing form validation in Next.js can be simplified using Formik, a form library for React, and Zod, a schema validation library. Together, they provi
    3 min read
  • How to add Calendar in Next.js ?
    Adding a calendar to a Next.js application enhances scheduling and event management. We can just install and use the available npm package. In this article, we are going to learn how we can add a calendar loader in NextJS. ApproachTo add our calendar we are going to use the react-calendar package. T
    2 min read
  • How to add ESLint in Next.js ?
    ESLint is a popular linting tool for identifying and fixing issues in JavaScript code. Adding ESLint to your Next.js project ensures that your code follows best practices and maintains a consistent style. This enhances code quality, helps catch errors early, and makes the codebase easier to maintain
    3 min read
  • React.js Chakra UI Form Validation
    Chakra UI is a simple and effective component-based library, that allows developers to build modern and attractive UI's for their website's frontends. Developers can simply use the components pre-defined in Chakra UI in their React.js Code to work faster and write less. The best part of Chakra UI is
    5 min read
  • How to add Tag Input in Next.js ?
    In this article, we are going to learn how we can add Tag input in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. Approach: To add our tag input, we are going to use the react-tag-input-component
    2 min read
  • How to add CodeBlock in Next.js ?
    In this article, we are going to learn how we can add CodeBlock in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditiona
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences