react表单验证
For almost every form that you create, you will want some sort of validation. In React, working with and validating forms can be a bit verbose, so in this article we are going to use a package called Formik to help us out!
对于您创建的几乎每种表单,您都需要某种验证。 在React中,使用和验证表单可能有些冗长,因此在本文中,我们将使用一个名为Formik的软件包来帮助我们!
TLDR (TLDR)
- Create a React project 创建一个React项目
- Add the Formik (and Yup) packages 添加Formik(和Yup)程序包
- Customize the Formik component with an onSubmit callback and a validate function for error messages 使用onSubmit回调和错误消息的validate函数来自定义Formik组件
- then display those error messages to the user.> View the final code on CodeSandbox! 然后向用户显示这些错误消息。> 在CodeSandbox上查看最终代码 !
Here's a sneak peak at what we are going to create.
这是我们将要创建的产品的一个潜行高峰。
创建React项目 ( Creating the React Project )
For this demo, I'll be using CodeSandbox. You can use CodeSandbox as well or use your local environment. Totally up to you.
对于此演示,我将使用CodeSandbox 。 您也可以使用CodeSandbox或使用您的本地环境。 完全取决于您。
Regardless of what you use for this demo, you need to start with a new React app using Create React App. In CodeSandbox, I'm going to choose to do just that.
无论您使用什么演示,都需要使用Create React App从一个新的React应用开始。 在CodeSandbox中,我将选择执行此操作。
安装必要的软件包 ( Installing Necessary Packages )
Now that we have our initial project created, we need to install three packages.
现在我们已经创建了初始项目,我们需要安装三个软件包。
- Formik - makes handling validation, error messages, and form submission easier Formik-使处理验证,错误消息和表单提交更加容易
- Email-validator - tiny package to validate emails (I hope this one is self-explanatory : ) 电子邮件验证程序 -用于验证电子邮件的小程序包(我希望这是不言自明的:)
- Yup - schema validator that is commonly used in conjuntion with Formik 是的 -即常用连词使用Formik架构验证
胶体 (Formik)
In your terminal, you'll need to install Formik.
在您的终端中,您需要安装Formik。
npm install Formik
I'll do the same in the CodeSandbox dependency GUI.
我将在CodeSandbox依赖项GUI中进行相同的操作。
电子邮件验证者 (Email-Validator)
npm install email-validator
Again installing from the CodeSandbox GUI.
再次从CodeSandbox GUI安装。