如何使用React Hook表单在React表单中添加表单验证功能

318 阅读4分钟

创建具有适当验证的表单可能很困难,也很有问题。但在这篇博文中,我将向你展示如何以一种简单明了的方式做到这一点。

我们将学习如何使用React和React Hook Form在表单中添加验证。

如何在React中创建一个表单

我们将首先使用Semantic UI库来创建一个表单。因此,让我们使用以下命令之一来安装它:

yarn add semantic-ui-react semantic-ui-css
## Or NPM
npm install semantic-ui-react semantic-ui-css

安装完毕之后,你需要将该包导入你的index.js文件,也就是你的应用程序的主入口文件:

import 'semantic-ui-css/semantic.min.css'

然后,我们需要一个有四个字的表单。所以,让我们用下面的代码来创建它:

import React from 'react';
import { Form, Button } from 'semantic-ui-react';

export default function FormValidation() {
    return (
        <div>
            <Form>
                <Form.Field>
                    <label>First Name</label>
                    <input placeholder='First Name' type="text" />
                </Form.Field>
                <Form.Field>
                    <label>Last Name</label>
                    <input placeholder='Last Name' type="text" />
                </Form.Field>
                <Form.Field>
                    <label>Email</label>
                    <input placeholder='Email' type="email" />
                </Form.Field>
                <Form.Field>
                    <label>Password</label>
                    <input placeholder='Password' type="password" />
                </Form.Field>
                <Button type='submit'>Submit</Button>
            </Form>
        </div>
    )
}

我们现在有一个表单。它有四个字,分别是名字、姓氏、电子邮件和密码。它还有一个提交按钮,用户可以提交表单:

如何安装React Hook Form

要安装React Hook Form,使用下面的命令:

npm install react-hook-form

如果你想了解更多关于该库的信息,你可以阅读文档。我们可以在React web和React Native应用中使用它。

我们在这里需要做的第一件事是从输入字段中获取数据并将其显示在控制台中。我们需要先导入这个包:

import { useForm } from "react-hook-form";

然后,我们需要对我们的应用程序中的 useForm 对象,像这样:

const { register, handleSubmit, formState: { errors } } = useForm();

现在,我们要使用 register 对象中的属性 **useForm**来注册我们的表单字段,它将是这样的:

<Form.Field>
                    <label>First Name</label>
                    <input
                        placeholder='First Name'
                        type="text"
                        {...register("firstName")}
                    />
                </Form.Field>

现在名字表单字段的键值是firstName。正如你所看到的,我们已经在寄存器中声明了它。对所有其他字段重复这一步骤:

import React from 'react';
import { Form, Button } from 'semantic-ui-react';
import { useForm } from "react-hook-form";

export default function FormValidation() {
    const { register, handleSubmit, formState: { errors } } = useForm();
    return (
        <div>
            <Form>
                <Form.Field>
                    <label>First Name</label>
                    <input
                        placeholder='First Name'
                        type="text"
                        {...register("firstName")}
                    />
                </Form.Field>
                <Form.Field>
                    <label>Last Name</label>
                    <input
                        placeholder='Last Name'
                        type="text"
                        {...register("lastName")}
                    />
                </Form.Field>
                <Form.Field>
                    <label>Email</label>
                    <input
                        placeholder='Email'
                        type="email"
                        {...register("email")}
                    />
                </Form.Field>
                <Form.Field>
                    <label>Password</label>
                    <input
                        placeholder='Password'
                        type="password"
                        {...register("password")}
                    />
                </Form.Field>
                <Button type='submit'>Submit</Button>
            </Form>
        </div>
    )
}

这就是到此为止的全部代码。四个字段,都已注册。

现在,在表单中,我们需要做一个onSubmit 事件。这意味着,如果我们点击底部的提交按钮,我们的表单数据应该被提交:

<Form onSubmit={handleSubmit(onSubmit)}>

我们还需要创建一个onSubmit函数,当提交按钮被点击或按下时,它将做一些特定的动作:

const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
  console.log(data);
}

因此,如果我们点击提交按钮,我们输入的数据将显示在控制台:

如何给我们的表单添加验证

现在,最后一个也是最令人期待的步骤来了。让我们来添加验证信息。

让我们从名字字段开始。我们将使用required和maxLength属性,它们是不言自明的:

  • Required表示该字段是必须的。
  • MaxLength 表示我们输入的字符的最大长度。
<input
  placeholder='First Name'
  type="text"
  {...register("firstName", { required: true, maxLength: 10 })}
/>

因此,将required 为true,maxLength 为10。然后,如果我们在提交表单时没有输入 "姓名",或者字符数超过10,它就会抛出一个错误。

但我们也需要添加错误信息本身。在 "名字 "表单字段后添加以下错误信息:

{errors.firstName && <p>Please check the First Name</p>}

这里,它将抛出一个错误。所以,让我们检查一下发生了什么:

你可以看到在 "名字 "字段后面的错误信息是 "请检查名字"。

重复这个过程,输入姓氏:

输入超过10个字符也会出现错误:

现在,我们需要为电子邮件和密码字段添加验证。在这里,我们将使用另一个属性叫做 Pattern.Pattern将包含一个正则表达式的值,它将根据表单中输入的数据进行检查。

pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 

这就是正则表达式模式的样子。它很难读,但这是一个用于电子邮件验证的模式。让我们在我们的应用程序中使用它:

<Form.Field>
                    <label>Email</label>
                    <input
                        placeholder='Email'
                        type="email"
                        {...register("email", 
                        { 
                            required: true,  
                            pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
                        })}
                    />
                </Form.Field>

在电子邮件表格字段中,添加这个模式:

输入错误的电子邮件格式会产生一个错误。但当我们输入正确的格式时,这个错误就会消失:

让我们对密码表单字段做同样的事情。对于密码字段,我们的条件是它应该包含一个大写字母,一个小写字母,而且字符数应该在6到15之间。如果我们输入的值没有通过这些检查,它就会出现错误:

 <Form.Field>
                    <label>Password</label>
                    <input
                        placeholder='Password'
                        type="password"
                        {...register("password", { 
                            required: true, 
                            pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/
                        })}
                    />
                </Form.Field>
                {errors.password && <p>Please check the Password</p>}

现在,我们所有的四个表单字段都完成了:

import React from 'react';
import { Form, Button } from 'semantic-ui-react';
import { useForm } from "react-hook-form";

export default function FormValidation() {
    const { register, handleSubmit, formState: { errors } } = useForm();
    const onSubmit = (data) => {
        console.log(data);
    }
    return (
        <div>
            <Form onSubmit={handleSubmit(onSubmit)}>
                <Form.Field>
                    <label>First Name</label>
                    <input
                        placeholder='First Name'
                        type="text"
                        {...register("firstName", { required: true, maxLength: 10 })}
                    />
                </Form.Field>
                {errors.firstName && <p>Please check the First Name</p>}
                <Form.Field>
                    <label>Last Name</label>
                    <input
                        placeholder='Last Name'
                        type="text"
                        {...register("lastName", { required: true, maxLength: 10 })}
                    />
                </Form.Field>
                {errors.lastName && <p>Please check the Last Name</p>}
                <Form.Field>
                    <label>Email</label>
                    <input
                        placeholder='Email'
                        type="email"
                        {...register("email",
                            {
                                required: true,
                                pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                            })}
                    />
                </Form.Field>
                {errors.email && <p>Please check the Email</p>}
                <Form.Field>
                    <label>Password</label>
                    <input
                        placeholder='Password'
                        type="password"
                        {...register("password", {
                            required: true,
                            pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/
                        })}
                    />
                </Form.Field>
                {errors.password && <p>Please check the Password</p>}
                <Button type='submit'>Submit</Button>
            </Form>
        </div>
    )
}

下面是整个代码供你参考。我们还可以为我们的错误信息添加一些样式--也许像这样:

结语

现在你知道如何在React表单中添加验证了。注意,React Hook Form只在功能组件中工作,而不是在类组件中。

你可以看看我的视频:让我们使用React和React Hook Form在表单中添加验证,这在我的YouTube频道上。

这里是GitHub 上的整个代码,供你参考。

学习愉快。