react表单验证_如何使用React和Formik验证登录表单

react表单验证

介绍 (Introduction)

In order to ensure that a form element of your web application is returning valid data, it is helpful to build automated validation into your code. This is true in React as well, as creating form validation early on can often save you from encountering errors down the road.

为了确保Web应用程序的表单元素正在返回有效数据,将自动验证内置到代码中很有帮助。 在React中也是如此,因为尽早创建表单验证通常可以使您免于遇到后续错误。

In React, working with and validating forms can be a bit verbose. To make your code more manageable, you can use a package like Formik to build your forms.

在React中,使用和验证表单可能有点冗长。 为了使代码更易于管理,可以使用Formik之类的程序包来构建表单。

In this tutorial, you will create a React project, add the Formik package, customize the Formik component with an onSubmit callback and a validate function for error messages, and then display those error messages to the user.

在本教程中,您将创建一个React项目,添加Formik包,使用onSubmit回调和错误消息的validate函数自定义Formik组件,然后将这些错误消息显示给用户。

By the end of this tutorial, you will have a project like this live example on CodeSandbox.

在本教程结束时,您将在CodeSandbox上有一个类似此示例的项目。

先决条件 (Prerequisites)

第1步-设置项目 (Step 1 — Setting up the Project)

Use Create React App to create a project. For the purposes of the tutorial, you can name your project validate-react-login-form.

使用Create React App创建一个项目。 就本教程而言,您可以将项目命名为validate-react-login-form 。

  • npx create-react-app validate-react-login-form

    npx create-react-app validate-react-login-form

You can now change into the project directory, start the node server, and view it in a web browser.

现在,您可以进入项目目录,启动节点服务器,然后在Web浏览器中查看它。

  • cd validate-react-login-form

    cd validate-react-login-form

  • npm start

    npm开始

If you have yarn installed, your message may instruct you to use yarn start instead of npm start. If you prefer to have npm instructions, it is possible to use --use-npm flag when creating your project. You can use either yarn or npm for this tutorial.

如果安装了yarn ,则您的消息可能会指示您使用yarn start而不是npm start 。 如果您更喜欢npm说明,则可以在创建项目时使用--use-npm标志 。 您可以在本教程中使用yarnnpm

You can also open this project directory in your favorite editor to create and modify files.

您也可以在收藏夹编辑器中打开此项目目录,以创建和修改文件。

Create React App will include several files, but for the purposes of this tutorial you will only be directly creating or modifying three files: index.js, index.css, and ValidatedLoginForm.js.

Create React App将包含多个文件,但是出于本教程的目的,您将仅直接创建或修改三个文件: index.jsindex.cssValidatedLoginForm.js

第2步-安装依赖项 (Step 2 — Installing Dependencies)

Now that we have our initial project created, we will install three packages: Formik, email-validator, and Yup.

现在,我们有我们最初的项目创建,我们将安装三个包: Formik电子邮件验证 ,并没错

Formik makes handling validation, error messages, and form submission more manageable.

Formik使处理验证,错误消息和表单提交的操作更加易于管理。

In your terminal, install Formik:

在您的终端中,安装Formik:

  • npm install formik

    npm安装formik

email-validator is a tiny package used to validate emails.

email-validator是用于验证电子邮件的微型软件包。

If your terminal, install email-validator:

如果是您的终端,请安装email-validator

  • npm install email-validator

    npm安装电子邮件验证器

Yup is a schema validator that is commonly used in conjunction with Formik.

Yup是一种模式验证器,通常与Formik结合使用。

In your terminal, install Yup:

在您的终端中,安装Yup:

  • npm install yup

    npm安装yup

Now that you’ve installed the necessary packages, you are ready to create the validated form component.

现在,您已经安装了必要的程序包,可以开始创建经过验证的表单组件了。

步骤3 —创建经过验证的表单组件 (Step 3 — Creating the Validated Form Component)

Now that you have installed the dependencies, you can start to write your ValidatedFormComponent. For now, you will create the basics and import it into the root file in the app to display it.

既然已经安装了依赖项,就可以开始编写ValidatedFormComponent 。 现在,您将创建基础并将其导入应用程序的根文件中以显示它。

To do this, you will do the following:

为此,您将执行以下操作:

  • Create a new functional component

    创建一个新的功能组件
  • Add dummy display content

    添加虚拟显示内容
  • Import it into index.js

    将其导入index.js

Create a new file in your src directory called ValidatedLoginForm.js. Inside of that file, add the basic code for a functional component:

src目录中创建一个名为ValidatedLoginForm.js的新文件。 在该文件的内部,添加功能组件的基本代码:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
import React from "react";

const ValidatedLoginForm = () => (
  <div>
    <h1>Validated Form Component</h1>
  </div>
);

export default ValidatedLoginForm;

Then, include it in your index.js file:

然后,将其包含在index.js文件中:

src/index.js
src / index.js
import ValidatedLoginForm from "./ValidatedLoginForm";

Next, reference the component:

接下来,参考组件:

src/index.js
src / index.js
<ValidatedLoginForm />

When you put all those pieces together, index.js will look like this:

当您将所有这些部分放在一起时, index.js将如下所示:

src/index.js
src / index.js
import React from "react";
import ReactDOM from "react-dom";

import ValidatedLoginForm from "./ValidatedLoginForm";

function App() {
  return (
    <div className="App">
      <h1>Validated Login Form</h1>
      <ValidatedLoginForm />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You will see the form component displayed:

您将看到显示的表单组件:

Now, let’s revisit ValidatedLoginForm.js to implement Formik.

现在,让我们重新访问ValidatedLoginForm.js以实现Formik。

First, import Formik, email-validator, and Yup in your new component:

首先,在您的新组件中导入Formik,email-validator和Yup:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
import { Formik } from "formik";
import * as EmailValidator from "email-validator"; // used when validating with a self-implemented approach
import * as Yup from "yup"; // used when validating with a pre-built solution

Now, let’s write the Formik tag with initial values. Think of initial values as setting your state initially.

现在,让我们用初始值编写Formik标签。 将初始值视为初始设置状态。

You’ll also need an onSubmit callback. This callback will take two parameters, values and an object, that you can destructure. The values represent the input values from your form. You will add some dummy code here to simulate an async login call, then log out what the values are.

您还需要一个onSubmit回调。 该回调将使用两个参数,值和一个对象,您可以对其进行分解。 这些值表示表单中的输入值。 您将在此处添加一些虚拟代码来模拟异步登录调用,然后注销这些值。

In the callback, call the setSubmitting function that was destructured from the second parameters. This will allow you to enable or disable the Submit button while the asynchronous login call is happening:

在回调中,调用从第二个参数解构的setSubmitting函数。 这将允许您在异步登录调用发生时启用或禁用Submit按钮:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<Formik
    initialValues={{ email: "", password: "" }}
    onSubmit={(values, { setSubmitting }) => {
      setTimeout(() => {
        console.log("Logging in", values);
        setSubmitting(false);
      }, 500);
    }}
  >
    <h1>Validated Login Form</h1>
  </Formik>

渲染道具 (Render Props)

The Formik component uses render props to supply certain variables and functions to the form that we create.

Formik组件使用渲染道具为我们创建的表单提供某些变量和函数。

In short, render props are used to pass properties to children elements of a component. In this case, Formik will pass properties to your form code, which is the child. Notice that you’re using destructuring to get a reference to several specific variables and functions.

简而言之,渲染道具用于将属性传递给组件的子元素。 在这种情况下,Formik会将属性传递给您的表单代码(即孩子)。 请注意,您正在使用解构来获取对几个特定变量和函数的引用。

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
{props => {
      const {
        values,
        touched,
        errors,
        isSubmitting,
        handleChange,
        handleBlur,
        handleSubmit
      } = props;

      return (
        <div>
          <h1>Validated Login Form</h1>
        </div>
      );
    }}

At this point, ValidatedLoginForm.js should resemble:

此时, ValidatedLoginForm.js应该类似于:

import React from "react";

import { Formik } from "formik";
import * as EmailValidator from "email-validator";
import * as Yup from "yup";

const ValidatedLoginForm = () => (
  <Formik
    initialValues={{ email: "", password: "" }}
    onSubmit={(values, { setSubmitting }) => {
      setTimeout(() => {
        console.log("Logging in", values);
        setSubmitting(false);
      }, 500);
    }}
  >
    {props => {
      const {
        values,
        touched,
        errors,
        isSubmitting,
        handleChange,
        handleBlur,
        handleSubmit
      } = props;

      return (
        <div>
          <h1>Validated Login Form</h1>
        </div>
      );
    }}
  </Formik>
);

export default ValidatedLoginForm;

步骤4 —显示表格 (Step 4 — Displaying the Form)

You can now start to write the code to display the form. The form will have two inputs (email and password), labels for each, and a submit button.

现在,您可以开始编写代码以显示表单。 该表单将具有两个输入(电子邮件和密码),每个输入的标签和一个提交按钮。

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
{props => {
      const {
        values,
        touched,
        errors,
        isSubmitting,
        handleChange,
        handleBlur,
        handleSubmit
      } = props;

      return (
        <form onSubmit={handleSubmit}>

          <label htmlFor="email">Email</label>
          <input
            id="email"
            name="email"
            type="text"
            placeholder="Enter your email"
          />

          <label htmlFor="password">Password</label>
          <input
            id="password"
            name="password"
            type="password"
            placeholder="Enter your password"
          />

          <button type="submit">
            Login
          </button>

        </form>
      );

    }}

Notice that the onSubmit is calling the handleSubmit from the props.

请注意, onSubmit正在从道具中调用handleSubmit

Earlier, it was mentioned that you could disable your submit button while the user is already attempting to log in. You can add that change now by using the isSubmitting property that you destructured from the previous props:

之前提到过,您可以在用户已经尝试登录时禁用“提交”按钮。您可以使用从以前的道具中isSubmitting属性来立即添加更改:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<button type="submit" disabled={isSubmitting}>
  Login
</button>

You can use the following CSS for your styles.css file:

您可以将以下CSS用于styles.css文件:

src/styles.css
src / styles.css
.App {
  font-family: sans-serif;
}

h1 {
  text-align: center;
}

form {
  max-width: 500px;
  width: 100%;
  margin: 0 auto;
}

label,
input {
  display: block;
  width: 100%;
}

label {
  margin-bottom: 5px;
  height: 22px;
}

input {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid #777;
}

input.error {
  border-color: red;
}

.input-feedback {
  color: rgb(235, 54, 54);
  margin-top: -15px;
  font-size: 14px;
  margin-bottom: 20px;
}

button {
  padding: 10px 15px;
  background-color: rgb(70, 153, 179);
  color: white;
  border: 1px solid rgb(70, 153, 179);
  transition: ease-in-out background-color 250ms, ease-in-out color 250ms;
}

button:hover {
  cursor: pointer;
  background-color: white;
  color: rgb(70, 153, 179);
}

Also, import styles.css in index.js.

另外,将styles.css导入index.js

src/index.js
src / index.js
import "./styles.css";

步骤5 —添加验证消息逻辑 (Step 5 — Adding Validation Messages Logic)

Now let’s validate our inputs. The first step is to determine what constraints we want to have on our input. Let’s start with email. Email input should:

现在让我们验证输入。 第一步是确定我们要对输入施加哪些约束。 让我们从电子邮件开始。 电子邮件输入应:

  • Be required.

    需要。
  • Look like a real email.

    看起来像一封真实的电子邮件。

Password input should:

密码输入应:

  • Be required.

    需要。
  • Be at least eight characters long.

    至少要八个字符。
  • Contain at least one number.

    至少包含一个数字。

We’ll cover two ways to create these messages, one manually and one using Yup.

我们将介绍两种创建这些消息的方法,一种是手动创建的,另一种是使用Yup的。

编写自己的密码验证解决方案 (Writing Your Own Password Validation Solution)

The first option is to create our validate function ourselves. The purpose of the function is to iterate through the values of our form, validate these values in whatever way we see fit, and return an errors object that has key value pairs of value and message.

第一种选择是自己创建我们的验证函数。 该函数的目的是遍历表单的值,以我们认为合适的任何方式验证这些值,并返回包含键值对valuemessageerrors对象。

Inside of the Formik tag, start with adding the following code. This will always add an Invalid email error for email.

在Formik标记内,首先添加以下代码。 这将始终为电子邮件添加一个Invalid email错误。

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};
    errors.email = "Invalid email";
    return errors;
  }}

Now, you can ensure that the user has input something for the email:

现在,您可以确保用户输入了电子邮件内容:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};
    if (!values.email) {
      errors.email = "Required";
    } 
    return errors;
  }}

Then, you can check that the email is a valid-looking email by using the email-validator package. This will look almost the same as the equivalent check for email:

然后,您可以使用email-validator软件包检查电子邮件是否为有效的电子邮件。 这看起来与电子邮件的等效支票几乎相同:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};
    if (!values.email) {
      errors.email = "Required";
    } else if (!EmailValidator.validate(values.email)) {
      errors.email = "Invalid email address.";
    }
    return errors;
  }}

That takes care of email, so you will work on the password form. You will first check that the user input something:

这样可以处理电子邮件,因此您将使用密码表单。 您将首先检查用户是否输入了以下内容:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};
    if (!values.password) {
      errors.password = "Required";
    } 
    return errors;
  }}

Now you need to ensure that the length is at least eight characters:

现在,您需要确保长度至少为八个字符:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    const passwordRegex = /(?=.*[0-9])/;
    if (!values.password) {
      errors.password = "Required";
    } else if (values.password.length < 8) {
      errors.password = "Password must be 8 characters long.";
    } 

    return errors;
  }}

Lastly, check that the password contains at least one number. For this, you can use regex:

最后,检查密码是否至少包含一个数字。 为此,您可以使用正则表达式:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};

    const passwordRegex = /(?=.*[0-9])/;
    if (!values.password) {
      errors.password = "Required";
    } else if (values.password.length < 8) {
      errors.password = "Password must be 8 characters long.";
    } else if (!passwordRegex.test(values.password)) {
      errors.password = "Invalid password. Must contain one number.";
    }

    return errors;
  }}

The completed file will look like this:

完成的文件如下所示:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validate={values => {
    let errors = {};
    if (!values.email) {
      errors.email = "Required";
    } else if (!EmailValidator.validate(values.email)) {
      errors.email = "Invalid email address.";
    }

    const passwordRegex = /(?=.*[0-9])/;
    if (!values.password) {
      errors.password = "Required";
    } else if (values.password.length < 8) {
      errors.password = "Password must be 8 characters long.";
    } else if (!passwordRegex.test(values.password)) {
      errors.password = "Invalid password. Must contain one number.";
    }

    return errors;
  }}

使用第三方密码验证解决方案 (Utilizing a Third-party Password Validation Solution)

You might have noticed that handling the validate logic on our own gets a bit verbose. You have to manually do all of the checks. Yup can save you some of this work. When using Yup, you will no longer see the Validate property, but instead use validationSchema.

您可能已经注意到,独自处理验证逻辑有些冗长。 您必须手动执行所有检查。 是的,可以为您节省一些工作。 使用Yup时,将不再看到Validate属性,而是使用validationSchema

Let’s start with email. Here is the equivalent validation using Yup:

让我们从电子邮件开始。 这是使用Yup的等效验证:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validationSchema={Yup.object().shape({
    email: Yup.string()
      .email()
      .required("Required")
  })}

Now, for password:

现在,输入密码:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
validationSchema={Yup.object().shape({
    email: Yup.string()
      .email()
      .required("Required"),
    password: Yup.string()
      .required("No password provided.")
      .min(8, "Password is too short - should be 8 chars minimum.")
      .matches(/(?=.*[0-9])/, "Password must contain a number.")
  })}

You’ve now explored two different methods for validating forms. Next you will update the code to display error messages.

现在,您已经探索了两种验证表单的方法。 接下来,您将更新代码以显示错误消息。

第6步-显示验证和错误消息 (Step 6 — Displaying Validation and Error Messages)

Now that we have the logic for creating error messages, we need to display them. You will need to update the inputs in your form to do this.

现在我们有了创建错误消息的逻辑,我们需要显示它们。 为此,您将需要更新表单中的输入。

We need to update several properties for both email and password inputs:

我们需要为电子邮件和密码输入更新几个属性:

  • value

    value

  • onChange

    onChange

  • onBlur

    onBlur

  • className

    className

将渲染道具应用于电子邮件字段 (Applying Render Props to the Email Field)

Let’s start by updating value, onChange, and onBlur. Each of these will use properties from the render props:

让我们从更新valueonChangeonBlur 。 其中每一个都将使用render道具的属性:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<input
  id="email"
  name="email"
  type="text"
  placeholder="Enter your email"
  value={values.email}
  onChange={handleChange}
  onBlur={handleBlur}
/>

Then you can add a conditional “error” class in case there are any errors. You can check for errors by looking at the errors object.

然后,如果有任何错误,您可以添加条件“错误”类。 您可以通过查看errors对象来检查errors

You can also check the touched property to see whether or not the user has interacted with the email input before showing an error message.

您还可以检查touched属性以查看用户在显示错误消息之前是否已与电子邮件输入进行了交互。

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<input
  id="email"
  name="email"
  type="text"
  placeholder="Enter your email"
  value={values.email}
  onChange={handleChange}
  onBlur={handleBlur}
  className={errors.email && touched.email && "error"}
/>

Lastly, if there are errors, you will display them to the user.

最后,如果有错误,则将其显示给用户。

The final result for the email field will look like this:

电子邮件字段的最终结果将如下所示:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<label htmlFor="email">Email</label>
<input
  id="email"
  name="email"
  type="text"
  placeholder="Enter your email"
  value={values.email}
  onChange={handleChange}
  onBlur={handleBlur}
  className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
  <div className="input-feedback">{errors.email}</div>
)}

将渲染道具应用于密码字段 (Applying Render Props to the Password Field)

Now you need to do the same with the password. These steps are similar to the email.

现在,您需要对密码进行相同的操作。 这些步骤类似于电子邮件。

The final result for the password field will look like this:

密码字段的最终结果将如下所示:

src/ValidatedLoginForm.js
src / ValidatedLoginForm.js
<label htmlFor="password">Password</label>
<input
  id="password"
  name="password"
  type="password"
  placeholder="Enter your password"
  value={values.password}
  onChange={handleChange}
  onBlur={handleBlur}
  className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
  <div className="input-feedback">{errors.password}</div>
)}

第7步-测试验证 (Step 7 — Testing the Validation)

Now that your form is complete, you are ready to test it out. You can start by clicking the button without entering anything. You will see validation messages:

现在您的表格已经完成,您可以进行测试了。 您可以单击按钮开始,而无需输入任何内容。 您将看到验证消息:

Now, we can get more specific for testing messages. Refresh your page to do this. Click inside of the email input, but don’t type anything:

现在,我们可以更具体地测试消息。 刷新页面以执行此操作。 单击电子邮件输入的内部,但不要输入任何内容:

Then, click away from the input. You should see the Required message pop up. Notice that this message doesn’t pop up automatically when the page loads. You only want to display error messages after the user has interacted with the input.

然后,单击远离输入。 您应该看到“ Required消息弹出。 请注意,页面加载时该消息不会自动弹出。 您只想在用户与输入进行交互之后显示错误消息。

Now, start to type. You will get a message about the email not being valid.

现在,开始输入。 您将收到一条有关电子邮件无效的消息。

Type in a valid email, and watch your error message go away.

输入有效的电子邮件,然后查看错误消息消失。

Now, do the same for password. Click on the input, then away, and you’ll get the required message.

现在,对密码执行相同的操作。 单击输入,然后离开,您将收到必需的消息。

Then, start typing and you’ll see the length validation.

然后,开始输入,您将看到长度验证。

Then, type eight or more characters that do not include a number, and you’ll see the must contain a number message.

然后,键入八个或更多不包含数字的字符,您将看到must contain a number消息。

Finally, add a number, and the error messages go away.

最后,添加一个数字,错误消息就会消失。

结论 (Conclusion)

You’ve now created a form with automatic validation in React, using Formik and Yum.

现在,您已经使用Formik和Yum在React中创建了具有自动验证的表单。

For more tutorials on React, check out our React Topic page.

有关React的更多教程,请查看我们的React Topic页面

翻译自: https://www.digitalocean.com/community/tutorials/how-to-validate-a-login-form-with-react-and-formik

react表单验证

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值