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
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
ReactJS Form Validation using Formik and Yup
Next article icon

React.js Chakra UI Form Validation

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 its reusability since it's a component-based library. Whenever we acquire user data through forms from our websites. It is important to check if the user has entered valid data. Form Validation is used for the same. We can perform form validations in Chakra UI through Form Control.

Approach: We will build a form using Chakra UI. We will use the following Components for the same.

  • FormControl: It is the top-level form component inside which we can place our inputs, buttons, and validations.
  • FormLabel: It allows us to write labels so that the user can know what the form consists of. For example - name, email, password, etc.
  • FormErrorMessage: It allows us to show an error to the user when the isInvalid property inside FormControl is set to true.

We will build a simple form. We will ask the user for his name, password, and email. The name will be a "required" input and the password must have a length of 8 characters. We will perform these necessary validations with help of the above components.

 

Setting up Application: 

Step 1: Create a new folder called chakra-form-validations. Open your terminal, navigate to this folder, and type in the following command:

npx create-react-app .

Step 2: This will install all the necessary starter files for you. Now we will install the Chakra UI library using the following command:

npm i @chakra-ui/react @emotion/react   npm i @emotion/styled framer-motion

Project Structure: The project structure should look like below:

Folder Structure

Note: We will be using Tailwind CSS for styling. For the same, inside the public folder, open index.html and use the playCDN link for Tailwind CSS inside the head tag.

index.html
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="utf-8" />     <link rel="icon"            href="%PUBLIC_URL%/favicon.ico" />     <script src= "https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp">       </script>     <meta name="viewport"            content="width=device-width, initial-scale=1" />     <meta name="theme-color"            content="#000000" />     <meta name="description"            content="Web site created using create-react-app" />     <link rel="apple-touch-icon"            href="%PUBLIC_URL%/logo192.png" />     <link rel="manifest"            href="%PUBLIC_URL%/manifest.json" />     <title>React App</title> </head>  <body>     <noscript>You need to enable JavaScript                  to run this app.</noscript>     <div id="root"></div> </body>  </html> 

Let us move to the examples.

Example 1: Password Validation

App.js
import { useState } from "react"; import { FormControl, FormLabel, FormErrorMessage,      FormHelperText, Input, Button } from "@chakra-ui/react";  function App() {     const [passwordLength, setPasswordLength] = useState("");     const handlePasswordChange = (e) => {         setPasswordLength(e.target.value);     }     const error = passwordLength.length < 8      return (         <div className="flex flex-col justify-center                          items-center my-44">             <h1 className="text-green-500 font-bold text-lg">                 GeeksforGeeks             </h1>             <h2 className="font-semibold mt-2">                 ReactJS Chakra UI Form Validation             </h2>             <FormControl className="shadow-lg p-8 rounded-lg mt-5"                 isRequired isInvalid={error}>                 <FormLabel>Name</FormLabel>                 <Input className="border border-gray-200                                    rounded-lg p-1 w-96"                     type="text" placeholder="Your name..." />                 <FormLabel className="mt-5">Password</FormLabel>                 <Input className="border border-gray-200                                    rounded-lg p-1 w-96"                     value={passwordLength}                     onChange={handlePasswordChange}                     type="password"                     placeholder="Your password..." />                 {error ? (                     <FormErrorMessage>                         Password is less than 8 characters...                     </FormErrorMessage>                 ) : (                     <FormHelperText>                         You are good to go...                     </FormHelperText>                 )}                 <Button className="bg-blue-600 text-white                                     p-1.5 mx-5 rounded-lg mt-5"                          type="submit">Submit</Button>             </FormControl>         </div>     ); }  export default App; 

Steps to run the application: Write the below code in the terminal to run the application:

npm run start

Output:

Output

Explanation: We are using the useState hook provided by React JS to store the length of our password. And inside error, we are storing the condition that the password length is greater than 8 characters. And then, we are simply checking if the error is true or false using a ternary operator and accordingly inform the user if his password is greater than 8 characters or not.

Example 2: Email Validation

  • App.js: Inside your src folder, open App.js, where we will perform our Form Validation. Below is the code for the same.
App.js
import { useState } from "react"; import { FormControl, FormLabel, Input, Button }      from "@chakra-ui/react";  function App() {     const [emailLength, setEmailLength] = useState("");     const handleEmailChange = (e) => {         setEmailLength(e.target.value);     }     const handleEmailError = (e) => {         e.preventDefault();          if (emailLength.indexOf("@") === -1) {             alert("Email should contain @");         }         else {             alert("You are good to go...");         }     }      return (         <div className="flex flex-col justify-center items-center my-44">             <h1 className="text-green-500 font-bold text-lg">                 GeeksforGeeks             </h1>             <h2 className="font-semibold mt-2">                 ReactJS Chakra UI Form Validation             </h2>             <FormControl className="shadow-lg p-8                                      rounded-lg mt-5"                                      isRequired>                 <FormLabel>Name</FormLabel>                 <Input className="border border-gray-200                                    rounded-lg p-1 w-96"                         type="text"                         placeholder="Your name..." />                 <FormLabel className="mt-5">Email</FormLabel>                 <Input className="border border-gray-200                                    rounded-lg p-1 w-96"                         value={emailLength}                         onChange={handleEmailChange}                         type="text"                         placeholder="Your email..." />                 <Button className="bg-blue-600 text-white p-1.5                                     mx-5 rounded-lg mt-5"                          type="submit"                     onClick={handleEmailError}>Submit</Button>             </FormControl>         </div>     ); }  export default App; 

Steps to run the application: Now, to run the project, use the command:

npm run start

Output:

Output

Explanation: In this example, we are storing the user's email with the help of the useState hook provided by React JS. And, when the user submits the form, we call the handleEmailError function using the onClick event. Inside this function, we are checking whether the "@" character exists in the mail or is missing using the indexOf String method. Accordingly, we are providing an alert box telling the user, if his email is correct or not.

Reference: https://chakra-ui.com/docs/components/form-control


Next Article
ReactJS Form Validation using Formik and Yup

P

pranavbapat2002
Improve
Article Tags :
  • Web Technologies
  • ReactJS

Similar Reads

  • React Suite Form Validation Default Check
    React Suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we’ll learn about React Suite Form Validation De
    3 min read
  • React Bootstrap Form Validation
    In Web Application Development, React-Bootstrap is the framework that helps to develop web pages in a more attractive form. While developing the application, we designed input fields and forms that need to be validated to maintain security. So, we can do this by using React Bootstrap Form Validation
    3 min read
  • React Suite Components Form validation
    React Suite is a front-end library, containing a wide range of React Components used in enterprise applications. This article discusses how the React suite's Form Validation helps developers add validation to forms. Form Validation involves providing prompt information to the user when there is an e
    7 min read
  • ReactJS Form Validation using Formik and Yup
    ReactJS Form Validation using Formik and Yup packages is one good approach for form validation. we can validate forms using controlled components. But it may be time-consuming and the length of the code may increase if we need forms at many places on our website. Formik is designed to manage forms w
    3 min read
  • React Suite Components Form validation Input
    React Suite is a collection of beautiful and customizable components for ReactJS that makes building user interfaces easier. One essential component is the Input. It handles form validation and user input smoothly, showing helpful error messages. This makes it perfect for creating strong and user-fr
    3 min read
  • React Chakra UI Form Switch
    Chakra UI Form Switch is a component provided by Chakra UI for creating toggle switches in React applications. It is an alternative to checkboxes, allowing users to switch between enabled and disabled states. Using the props of the Chakra UI Form Switch we can customize its appearance by changing th
    3 min read
  • Chakra UI Form Select
    Chakra UI is a modern UI building library that comprises of many predefined customizable components. One of those components are 'Select'. Select component in Chakra UI allows an user to choose a value from a set of defined values. 'RadioGroup' does somewhat similar thing. However, In the case where
    5 min read
  • How to Add Form Validation In Next.js ?
    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 qual
    3 min read
  • Create a Form using React JS
    Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
    5 min read
  • JavaScript Form Validation
    JavaScript form validation checks user input before submitting the form to ensure it's correct. It helps catch errors and improves the user experience. What we are going to CreateIn this article, we will guide you through creating a form validation application. This application will validate essenti
    11 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