当前位置: 首页 > 编程日记 > 正文

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

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 统一字段验证

相关文章:

UISearchBar和 UISearchDisplayController的使用

感觉好多文章不是很全面&#xff0c;所以本文收集整合了网上的几篇文章&#xff0c;感觉有互相补充的效果。 如果想下载源码来看&#xff1a;http://code4app.com/search/searchbar 。本源码与本文无关 1、searchBar 本例子实现布局&#xff1a;上面是一个navigationController…

iOS 获取指定时间的前后N个月

https://www.cnblogs.com/SUPER-F/p/7298548.html 正数为后 负数为前 -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month { NSDateComponents *comps [[NSDateComponents alloc] init]; [comps setMonth:month]; NSCalendar *calender …

JS高级程序设计第五章读书笔记

1.引用类型的值&#xff08;对象&#xff09;是引用类型的一个实例。在ES中&#xff0c;引用类型是一种数据结构&#xff0c;用于将数据和功能组织在一起。它们也长被称为类&#xff0c;但这并不妥当。因为ES在技术层面上是一门面对对象的语言&#xff0c;但它并不具备传统的面…

使用Tape和Vue Test Utils编写快速的Vue单元测试

by Edd Yerburgh埃德耶堡(Edd Yerburgh) 使用Tape和Vue Test Utils编写快速的Vue单元测试 (Write blazing fast Vue unit tests with Tape and Vue Test Utils) Tape is the fastest framework for unit testing Vue components.磁带是用于Vue组件进行单元测试的最快框架。 I…

js去除数组中重复值

//第三种方法加强版 Array.prototype.distinctfunction(){ var sameObjfunction(a,b){ var tag true; if(!a||!b)return false; for(var x in a){ if(!b[x]) return false; if(typeof(a[x])object){ tagsameObj(a[x],b[x]); }else{ if(a[x]!b[x]) return false; } } return ta…

CXFServlet类的作用

CXFServlet是Apache CXF框架中的一个核心组件,用于处理HTTP请求并将它们转换为Web服务调用。通过配置CXFServlet,你可以轻松地部署和管理SOAP和RESTful Web服务。

了解jvm对编程的帮助_这是您对社会责任编程的了解

了解jvm对编程的帮助by ?? Anton de Regt由?? 安东德雷格 这是您对社会责任编程的了解 (This is what you need to know about Socially Responsible Programming) 您的才华比银行帐户中的零值多 (Your talent is worth more than lots of zeroes in your bank account) L…

解压和生成 system.imgdata.img ( ext4格式)

另一篇文章讲述了如何解压和生成system.img&#xff0c; 那是针对yaffs2格式的文件系统镜像。 目前越来越多的Android手机放弃了nand, 更多采用了emmc为内部存储设备。 以emmc为存储设备的android手机&#xff0c;其文件系统(/system,/data两个分区&#xff09;一般采用ext4格式…

简单分析beyond作曲

本人绝对是业余的哈 业余到什么水平呢&#xff1f;正在练习爬格子&#xff0c;还是一个星期练几次那种 先说下《海阔天空》 6&#xff0c;5&#xff0c;4&#xff0c;3 1&#xff0c;2&#xff0c;3&#xff0c;4 简单是简单得不得了&#xff0c;声从低到高&#xff0c;然后再从…

1 OC 对象的本质(一个NSObject 对象占用的内存大小)

1 前言 目录 1 前言 2 一个NSObject占用多少内存 3 为什么呢 &#xff1f; 4 如何在内存中看呢&#xff1f; OC 的面向对象都是基于C/C 的数据结构实现的 结构体 2 clang 命令转换成c 代码 clang -rewrite-objc main.m -o main.cpp 以上的命令是不分平台进行编译的&…

Xiki:一个开发人员寻求增强命令行界面的能力

by Craig Muth通过克雷格穆斯(Craig Muth) Xiki&#xff1a;一个开发人员寻求增强命令行界面的能力 (Xiki: one developer’s quest to turbocharge the command line interface) I was sitting with my friend Charles in a trendy cafe next to Golden Gate Park in San Fra…

2 OC 对象的本质(一个Student 占用的内存大小)

一 Student 占用的内存空间 补充&#xff1a; 1 成员变量占用字节的大小&#xff1a; 2 内存对齐的规则&#xff1a;结构体的内存大小必须是最大成员变量的内存的倍数。 一个 Student 类,继承自NSObject&#xff0c;有两个属性&#xff0c;首先要知道&#xff0c;int 类型占用…

jdk动态代理源码学习

最近用到了java的动态代理&#xff0c;虽然会用&#xff0c;但不了解他具体是怎么实现&#xff0c;抽空看看了看他的源码。 说到Java的动态代理就不能不说到代理模式&#xff0c;动态代理也就是多了一个’动态’两字,在《大话设计模式》中不是有这句话吗&#xff1f;“反射&…

20162313苑洪铭 第一周作业

20162313苑洪铭 20016-2017-2 《程序设计与数据结构》第1周学习总结 教材学习内容总结 本周观看教材绪论 主要在教我建立一个简单的java程序 内容是林肯的名言 虽然看起来很简单 但是实际上问题重重 总而言之 这一周全是在出现故障的 教材学习中的问题和解决过程 教材学习好像并…

测试驱动开发 测试前移_测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做...

测试驱动开发 测试前移by Navdeep Singh通过Navdeep Singh 测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做 (Test-driven development might seem like twice the work — but you should do it anyway) Isn’t Test Driven Development (TDD) twice the wor…

3 OC 属性和方法

1 OC 的属性的生成 interface Student:NSObject {publicint _no;int _age;}property (nonatomic,assign)int height;end 当我们使用property 的时候&#xff0c;那么系统会自动的在其内部生成个属性 xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main.c…

ios绘图时的坐标处理

在iOS中&#xff0c;进行绘图操作时&#xff0c;一般主要是在UIView:drawRect中调用 UIGraphicsBeginImageContextWithOptions等一系列函数&#xff0c;有时候直接画图就行&#xff0c;比如UIImage的drawRect等&#xff0c;有时候需要进行稍微复杂的操作&#xff0c;比如颜色混…

mongoDB数据库操作工具库

/* Mongodb的数据库工具类 */ var client require(mongodb).MongoClient;function MongoUtil() { this.url"mongodb://localhost:27017/storage";//在本地新建数据库storage&#xff0c;此后插入的数据都在storage中 }MongoUtil.prototype.connectfunction(callback…

开源许可证 如何工作_开源许可证的工作方式以及如何将其添加到您的项目中...

开源许可证 如何工作by Radu Raicea由Radu Raicea 开源许可证的工作方式以及如何将其添加到您的项目中 (How open source licenses work and how to add them to your projects) Recently, there was some exciting news for developers around the world. Facebook changed t…

通过API文档查询Math类的方法,打印出近似圆,只要给定不同半径,圆的大小就会随之发生改变...

package question;import java.util.Scanner; import java.lang.Math;public class MathTest {/*** 未搞懂* param args*/public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("请输入圆的半径:");Scanner in new Scanne…

4 OC 中的内存分配以及内存对齐

目录 一 OC 中的内存分配 一 OC 中的内存分配 student 结构体明明是20&#xff1f;为什么是24个字节&#xff0c;因为结构体会按照本身成员变量最大的内存进行对齐&#xff0c;最大成员变量是8个字节&#xff0c;因此就是8的倍数&#xff0c;24个字节。 class_getInstanc…

JDE函数--GetUDC(B函数)

GetUDC使用方式&#xff1a; 转载于:https://www.cnblogs.com/GYoungBean/p/4117965.html

k8s crd构建方法_告诉您正在构建没人想要的东西的8种方法(以及处理方法)

k8s crd构建方法by Geoffrey Bourne杰弗里伯恩(Geoffrey Bourne) 告诉您正在构建没人想要的东西的8种方法(以及处理方法) (8 ways to tell you’re building something nobody wants (and what to do about it)) Building something users want is hard — damn hard. They ar…

iOS开发 - 线程与进程的认识与理解

进程&#xff1a; 进程是指在系统中正在运行的一个应用程序&#xff0c;比如同时打开微信和Xcode&#xff0c;系统会分别启动2个进程;每个进程之间是独立的&#xff0c;每个进程均运行在其专用且受保护的内存空间内;线程&#xff1a; 一个进程要想执行任务&#xff0c;必须得有…

Winform开发中常见界面的DevExpress处理操作

我们在开发Winform程序的时候&#xff0c;需要经常性的对界面的一些控件进行初始化&#xff0c;或者经常简单的封装&#xff0c;以方便我们在界面设计过程中反复使用。本文主要介绍在我的一些项目中经常性的界面处理操作和代码&#xff0c;以便为大家开发的时候提供必要的参考。…

5 OC 中的三种对象

目录 OC 中对象的分类 一 instance 对象 二 类对象 三 元类对象 总结: OC 中对象的分类 instance 对象 类对象 元类对象 一 instance 对象 内存中包含哪些信息 isa 指针 其他成员的变量Student *stu1 [[Student alloc]init]; 以上的stu1 就是实例对象 二 类对象 以…

travis ci_如何使用Travis CI和GitHub进行Web开发工作流程

travis ciby Vijayabharathi Balasubramanian通过Vijayabharathi Balasubramanian 如何使用Travis CI和GitHub进行Web开发工作流程 (How to use Travis CI and GitHub for your web development workflow’s heavy lifting) It’s common to hack together apps on CodePen wh…

android.view.ViewRoot$CalledFromWrongThreadException的解决办法

android 是不允许子线程直接更新UI的&#xff0c;如果一定要在子线程直接更新UI就会出现android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.大概意思就是说 只有原来创建找个视图hierarchy的…

6 OC中 isa 和 superclass 的总结

目录 一 关于isa 和 superclass 的总结 二 为什么基类的metaclass 的superclass 指向的是基类的类 三 isa 的细节问题 总结如下&#xff1a; instance 的isa 指向是classclass 的isa 指向是metaclassmetaclass 的isa指向是基类的imetaclassclass 的superclass 指向的是父类…