Open In App

React.js Chakra UI Form Validation

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads