react 统一字段验证

by Gosha Arinich

通过Gosha Arinich

如何使用React的受控输入进行即时表单字段验证 (How to use React’s controlled inputs for instant form field validation)

Controlled inputs enable simple things, like disabling the Submit button when some fields are missing or invalid.

受控输入可启用简单的功能,例如在某些字段丢失或无效时禁用“提交”按钮 。

But we’re not stopping there, of course.

但是,我们当然不止于此。

While a disabled button is nice, the user might not know why they can’t click that button. They might not know what mistake they made that disabled it or even which field is causing it.

尽管禁用的按钮很不错,但用户可能不知道为什么无法单击该按钮。 他们可能不知道自己犯了什么错误而导致禁用它,甚至是哪个字段导致了它。

And that ain’t pretty. We absolutely have to fix that.

那不是很漂亮。 我们绝对必须解决该问题。

受控输入的基础 (The basics of controlled inputs)

Using controlled inputs implies we are storing all the input values in our state. We can then evaluate a particular condition with every value change, and do something based on it. Previously, all we did was disable the button.

使用受控输入意味着我们将所有输入值存储在状态中。 然后,我们可以评估每个值变化的特定条件,并根据此条件执行某些操作。 以前,我们所做的就是禁用按钮。

We used a simple expression to compute whether the button should be disabled (for example, when either the email or password field was empty):

我们使用一个简单的表达式来计算是否应禁用按钮(例如,当电子邮件或密码字段为空时):

const { email, password } = this.state;const isEnabled =  email.length > 0 &&  password.length > 0;
<button disabled={!isEnabled}>Sign up<;/button>

It got the job done. Now, to mark the bad inputs, we need to ask ourselves a couple of questions.

它完成了工作。 现在,为了标记错误的输入,我们需要问自己几个问题。

错误将如何显示? (How will the errors be shown?)

This is an important question to ask yourself, as different requirements might warrant different error representations.

这是一个很重要的问题,因为不同的要求可能会导致不同的错误表示。

There are many ways to show input errors. For example, you could:

有很多显示输入错误的方法。 例如,您可以:

  • Display an ❌显示an
  • Mark the inputs red that contain bad data将包含不良数据的输入标记为红色
  • Display errors right next to the relevant inputs在相关输入旁边显示错误
  • Display a list of errors at the top of the form在表单顶部显示错误列表
  • Any combination of the above, or something else!以上的任何组合,或其他!

Which one should you use? Well, it’s all about the experience you want to provide. Pick what you want.

您应该使用哪一个? 好吧,这一切都与您要提供的体验有关。 选择您想要的。

For the purpose of this post, I’m going to use the simplest one — marking the bad inputs red, without anything else.

出于这篇文章的目的,我将使用最简单的一个-将不良输入标记为红色,没有其他任何内容。

错误将如何表示? (How will the errors be represented?)

The way you want to display errors influences how you might represent them.

您想要显示错误的方式会影响您如何表示错误。

To indicate whether a particular input is valid, without any additional information as to why it might be invalid, something like this will suffice:

为了表明特定输入是否有效,而又没有任何有关为什么输入无效的附加信息,可以满足以下条件:

errors: {  name: false,  email: true,}

false means no errors or entirely valid; true means a field is invalid.

false表示没有错误或完全有效; true表示字段无效。

In the future, if we decide we need to store the reason something was invalid, we can replace the true/false with a string containing an error message.

将来,如果我们决定需要存储某些无效原因,则可以将真/假替换为包含错误消息的字符串。

但是如何创建此错误对象? (But how is this error object created?)

Now that we know how we want to display the errors AND know how to represent them, there’s something crucial missing.

现在,我们知道了如何显示错误并知道如何表示错误,这里有一些关键的缺失。

How to actually create errors.

如何实际创建错误。

Or, put another way: how do we take existing inputs, validate them, and get the error object we need?

或者,换一种说法:我们如何获取现有输入,对其进行验证并获得所需的错误对象?

We are going to need a validation function for that. It will accept the current values of the fields and return the errors object to us.

我们将需要一个验证功能 。 它将接受字段的当前值,并将errors对象返回给我们。

We’ll continue with the sign-up form example. Recall that we had this:

我们将继续使用注册表单示例。 回想一下,我们有:

const { email, password } = this.state;const isEnabled =  email.length > 0 &&  password.length &gt; 0;

We can, in fact, turn that piece of logic into a validation function that will:

实际上,我们可以将逻辑转换为验证功能,该功能将:

  • Have email: true if email is empty, and

    email: true如果电子邮件为空,则为email: true ,并且

  • Have password: true if password is empty

    拥有password: true如果密码为空,则为password: true

function validate(email, password) {  // true means invalid, so our conditions got reversed  return {    email: email.length === 0,    password: password.length === 0,  };}

剩下的一块 (The remaining piece)

There’s one piece of the puzzle remaining.

剩下的难题之一。

We have a validation function and we know how we want to show errors. We also have a form.

我们具有验证功能,并且知道如何显示错误。 我们也有一个表格。

Now it’s time to connect the dots.

现在该连接点了。

Step 1: Run the validator in render.

步骤1:render运行验证器。

It’s no use having the validate function if we never call it. We want to validate the inputs every time (yes, every time) the form is re-rendered — perhaps there’s a new character in the input.

如果我们从不调用validate函数,则没有用。 我们希望每次(是,每次)重新渲染表单时都要验证输入-也许输入中有一个新字符。

const errors = validate(this.state.email, this.state.password);

Step 2: Disable the button.

步骤2:停用按钮。

This is a simple one. The button should be disabled if there are any errors (that is, if any of the errors values are true ).

这很简单。 如果有任何错误(即,如果任何errors值均为true ),则应禁用该按钮。

const isEnabled = !Object.keys(errors).some(x => errors[x]);

Step 3: Mark the inputs as erroneous.

步骤3:将输入标记为错误。

This can be anything. In our case, adding an error class to the bad inputs is enough.

这可以是任何东西。 在我们的例子中,将error类添加到error的输入中就足够了。

<input  className={errors.email ? "error" : ""}  .../>

We can also add a simple CSS rule:

我们还可以添加一个简单CSS规则:

.error { border: 1px solid red; }

还有一件事 (One more thing)

If you look at the JS Bin above, you may notice something odd. The fields are marked red by default, because empty fields are invalid.

如果您查看上面的JS Bin,您可能会发现有些奇怪。 默认情况下,这些字段标记为红色,因为空字段无效。

But we never even gave the user a chance to type first! Also, the fields are red when focused on for the first time.

但是我们甚至从未给用户提供第一次输入的机会! 此外,首次聚焦时这些字段为红色。

This is not great for UX.

这对UX来说不是很好。

We are going to fix this by adding the error class if the field was in focus at least once but has since been blurred. This ensures that the first time a user focuses on the field, the error won’t appear right away. Instead, it will only pop up when the field is blurred. On subsequent focuses, though, the error would appear.

我们将通过添加error类来解决此问题,如果该字段至少一次成为焦点,但此后一直被模糊。 这样可以确保用户第一次关注该字段时,该错误不会立即出现。 取而代之的是,它只会在视场模糊时弹出。 但是,在随后的重点上,将出现错误。

This is easily achievable by using the onBlur event and state to keep track of what was blurred.

通过使用onBlur事件和状态来跟踪模糊的内容,这很容易实现。

class SignUpForm extends React.Component {  constructor() {    super();    this.state = {      email: '',      password: '',      touched: {        email: false,        password: false,      },    };  }
// ...
handleBlur = (field) => (evt) => {    this.setState({      touched: { ...this.state.touched, [field]: true },    });  }
render()    const shouldMarkError = (field) => {      const hasError = errors[field];      const shouldShow = this.state.touched[field];
return hasError ? shouldShow : false;    };
// ...
<input      className={shouldMarkError('email') ? "error" : ""}      onBlur={this.handleBlur('email')}
type="text"      placeholder="Enter email"      value={this.state.email}      onChange={this.handleEmailChange}    />  }}

Not so hard, right?

没那么难吧?

最后的润色 (Final touches)

Note that shouldMarkError only affects field presentation. The status of the submit button still depends only on validation errors.

请注意, shouldMarkError仅影响字段表示。 提交按钮的状态仍然仅取决于验证errors

Want to add a nice final touch? You could force display of errors in all fields, regardless of whether they have been in focus, when the user hovers or clicks a disabled submit button. Now go try it out for yourself.

想要添加一个不错的最终效果吗? 当用户悬停或单击禁用的提交按钮时,可以强制在所有字段中显示错误,而不管它们是否已成为焦点。 现在,亲自尝试一下。

I originally published this on my blog at goshakkk.name

我最初将此内容发布在我的博客上goshakkk.name

If you are digging this, give me some claps and check out my series on handling forms with React. You can also subscribe to get new posts straight in your inbox.

如果您正在研究这个问题,请给我一些鼓掌,并查看我有关使用React处理表单的系列文章 。 您也可以订阅 ,直接在收件箱中获取新帖子。

翻译自: https://www.freecodecamp.org/news/how-to-use-reacts-controlled-inputs-for-instant-form-field-validation-b1c7b033527e/

react 统一字段验证

react 统一字段验证_如何使用React的受控输入进行即时表单字段验证相关推荐

  1. 字段校验 css样式_CSS伪类:根据输入的表单字段样式

    字段校验 css样式 The following is an extract from our book, CSS Master, written by Tiffany B. Brown. Copie ...

  2. react 组件引用组件_自定位React组件

    react 组件引用组件 While React has ways to break the hatch and directly manipulate the DOM there are very ...

  3. react中样式冲突_如何通过React中的样式使您的应用漂亮

    react中样式冲突 by Vinh Le 由Vinh Le 如何通过React中的样式使您的应用漂亮 (How to make your apps pretty with styling in Re ...

  4. postman关闭ssl验证_【第5期】springboot:苹果内购服务端验证

    ​苹果内购: 只要你在苹果系统购买APP中虚拟物品(虚拟货币,VIP充值等),必须通过内购方式进行支付,苹果和商家进行三七开 验证模式有两种: Validating Receipts With the ...

  5. Vue 正则表达式验证表单字段(如用户名/密码/真实姓名/身份证/手机号/邮箱)的合法性

    1. 给页面表单对象添加验证属性 由于我的项目使用的el-form,则给el-form添加属性  :rules="registerRules" ref="register ...

  6. react项目开发步骤_成为专业React开发人员的31个步骤

    react项目开发步骤 我为达到可雇用水平而进行的每个项目和课程. (Every single project and course I took to reach a hireable level. ...

  7. react 日期怎么格式化_手写React的Fiber架构,深入理解其原理

    熟悉React的朋友都知道,React支持jsx语法,我们可以直接将HTML代码写到JS中间,然后渲染到页面上,我们写的HTML如果有更新的话,React还有虚拟DOM的对比,只更新变化的部分,而不重 ...

  8. jsonp react 获取返回值_谈谈对 React 新旧生命周期的理解

    前言 在写这篇文章的时候,React 已经出了 17.0.1 版本了,虽说还来讨论目前 React 新旧生命周期有点晚了,React 两个新生命周期虽然出了很久,但实际开发我却没有用过,因为 Reac ...

  9. react 组件引用组件_动画化React组件

    react 组件引用组件 So, you want to take your React components to the next level? Implementing animations c ...

最新文章

  1. php 如何发送json数据格式,Php如何使用curl发送json格式数据实例
  2. Matlab 自带机器学习算法汇总
  3. 面试官 | 什么是 Lambda?该如何使用?
  4. java future接口_java Future 接口介绍
  5. 基于visual Studio2013解决面试题之0507字符串转整数
  6. CrackMe011
  7. 句柄详解,什么是句柄?句柄有什么用?
  8. CMD命令制定打印机,打印测试页
  9. php ppt read_PHP如何读取PPT?
  10. java 华氏温度转换为摄氏温度
  11. cygwin 复制粘贴
  12. docker镜像(第二天)
  13. 大数据24小时:地质局发布地质大数据共享平台,科大讯飞将语音识别植入腾讯小Q机器人
  14. 表格提示html内容消失,如何解决Word里面的表格插入题注后页面上内容消失、无法编辑的问题...
  15. 使用Neo4j+InteractiveGraph实现豆瓣电影知识图谱可视化
  16. MSF Risk Management Discipline
  17. K8s——kubernetes集群中ceph集群使用【下】
  18. 零、一些常用的英文名称
  19. IDEA从零到精通(16)之IDEA中用Spring Initializr创建springboot项目
  20. 如何使用webshell方式登录腾讯云Linux轻量应用服务器实例?

热门文章

  1. Window对象中setInterval()和setTimeout()的区别
  2. JavaScript中substr()和substring的区别
  3. uniapp移动端H5在线预览PDF等文件实现源码及注解
  4. CSS动画效果无限循环放大缩小
  5. [微信小程序]下拉菜单
  6. iOS 改变字符串中数字的颜色
  7. gdb图形化调试工具总结
  8. Spring从菜鸟到高手(四)(上)使用JdbcTemplate类实现用户登陆验证、批量更新
  9. 基于Idea从零搭建一个最简单的vue项目
  10. sql语句中having的作用是?