React.js Chakra UI表单验证

React.js Chakra UI表单验证

Chakra UI 是一个简单有效的基于组件的库,允许开发人员为网站前端构建现代和吸引人的UI。开发人员可以在React.js代码中简单地使用Chakra UI中预定义的组件,以提高工作速度并减少编写量。Chakra UI的最大优点是可重用性,因为它是一个基于组件的库。每当通过表单从网站上获取用户数据时,重要的是检查用户是否输入了有效的数据。表单验证用于此目的。我们可以通过Form Control在Chakra UI中执行表单验证。

方法: 我们将使用Chakra UI构建一个表单。我们将使用以下组件来完成。

  • FormControl: 它是顶级表单组件,在其中我们可以放置我们的输入、按钮和验证。
  • FormLabel: 它允许我们编写标签,以便用户知道表单包含的内容。例如 – 姓名,电子邮件,密码等。
  • FormErrorMessage: 当FormControl中的isInvalid属性设置为true时,它允许我们向用户显示错误信息。

我们将构建一个简单的表单。我们将向用户询问其姓名、密码和电子邮件。姓名将是一个“必填”输入,而密码必须具有8个字符的长度。我们将使用上述组件来执行这些必要的验证。

设置应用程序:

步骤1: 创建一个名为 chakra-form-validations 的新文件夹。打开你的终端,导航到该文件夹,并输入以下命令:

npx create-react-app .

步骤2:

这将为您安装所有必需的入门文件。现在,我们将使用以下命令安装Chakra UI库:

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

项目结构:

项目的结构应该如下所示:

React.js Chakra UI表单验证

注意: 我们将使用 Tailwind CSS 进行样式设计。为此,在 public 文件夹中,打开 index.html 并在 head 标签内使用 playCDN 链接来引入 Tailwind CSS

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>

让我们来看示例。

示例1:密码验证

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;

运行应用程序的步骤: 在终端中写入以下代码以运行应用程序:

npm run start

输出:

React.js Chakra UI表单验证

说明: 我们正在使用React JS提供的useState hook来存储密码的长度。在error内部,我们存储了密码长度大于8个字符的条件。然后,我们简单地使用三元操作符检查error是true还是false,并相应地告知用户他的密码是否大于8个字符。

示例2:电子邮件验证

  • App.js: 在你的src文件夹中,打开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;

运行应用程序的步骤: 现在,要运行项目,请使用以下命令:

npm run start

输出:

React.js Chakra UI表单验证

解释: 在这个示例中,我们使用React JS提供的useState hook来存储用户的电子邮件。当用户提交表单时,我们使用onClick事件调用handleEmailError函数。在这个函数内部,我们使用indexOf字符串方法来检查邮件中是否存在或缺少“@”字符。根据结果,我们会通过弹出框告诉用户他的电子邮件是否正确。

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程