React.js Chakra UI Form Validation
Last Updated :
28 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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read