React.js Chakra UI Form Validation
Last Updated : 24 Apr, 2025
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
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