反应和验证库 [英] React and Validation library

查看:23
本文介绍了反应和验证库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR:React 提供受控组件 HOC,这是 NPM 中 React 验证库的基本思想.但是,弱点是与现有组件的集成,例如 React Select 和自定义显示错误位置留言

我正在从传统的 jQuery 和 PHP 编码迁移(多年来用于真实和大型项目,而不是学生学习玩代码).我大部分时间都在 FORM 上,因为客户的要求总是关于 FORM.

现在有了 FORM,最重要的部分是验证方法/插件.首先忘记一些人告诉我们使用 React 你可以轻松地做受控组件,所以我们不需要验证插件".我们在生产中的 FORM 需要数百个带有许多选项卡的字段(例如人员表单或一些疯狂的组织报告),因此每个字段编码是不切实际的,就像传统的 js 编码来验证表单一样.

来到图书馆,我测试了一下,发现这三个可能已经足够了.

  1. 反应验证
  2. 反应验证混合
  3. Formsy

我不会详细介绍这些库,但它们的工作方式是相似的.我们必须为 input、select、textarea 和 form 创建一个组件才能使它们工作.在 Input 组件中,我们定义了 Input 边框如何更改类以使边框错误为红色以及错误消息如何出现(在 Input 下方的 div 或 span 中).

(还有其他验证库,但他们的方法是对表单进行 json 验证,甚至使用 json 创建表单,这不是我的选择,因为我只想通过输入中的一个简单属性来验证表单,例如 [required, email],不要在大量定义 json 上浪费时间

现在我在这些情况下坚持使用这种技术:

1.与现有优秀组件集成

我从 NPM 下载了优秀的组件来解决一些特定的功能(比如 React Select).现在开始真正的工作,我们必须验证这些自定义组件的输入.这是一项额外的工作,我们必须将验证集成到任何发现的额外组件中.我一头撞在墙上想出使用 HOC 来验证 React Select 像这样(React-验证码).为了使这项工作正常进行,我必须修改 origin HOC 以创建自定义 HOC.

//定义自己的 Input 组件function MySelect({ error, isChanged, isUsed, ...selectProps }) {返回(<div><Select onChange={selectProps.onChange.bind(this)} {...selectProps} {...( isChanged && isUsed && error ? {类名:`is-invalid-input ${selectProps.className}`} : { className: selectProps.className } )}/><input type="hidden" {...selectProps}/>{isChanged &&isUsed &&错误}

)}const MyValidationSelect = controlSelect(MySelect);//我的自定义 HOC

现在,我想不出更多在未来使用这种技术的方法了.想象一下,我们有项目并且需要一个额外的组件.我们没有太多时间来编写我们自己的代码,所以下载一个库.BOOM*,我们拼命想弄清楚如何使自定义组件验证.我们会将时间浪费在副项目"上,而不是主要任务(客户端请求功能)上.

2.验证消息的自定义位置

组件很好,但它也将代码包装在布局中.错误信息必须是输入组件的一部分.现在是困难的部分,一些疯狂的客户端需要将错误消息放在表单顶部或模式框中.在这种情况下,如果在组件中使用包装输入和错误,我仍然想不出解决方案.

3.我的肮脏解决方案

jQuery 出现的时间足以让 jQuery lib 变得成熟.jquery 验证可以通过所谓的 jQuery Validation 解决.使用这个库(自定义错误位置、自定义字段、自定义验证器、自定义错误格式(不仅仅是 css 东西)...)可以轻松优雅地解决我们为验证考虑的任何情况.

我只是在 ComponentDidMount 中使用 React 表单进行 jQuery 验证,它按原样工作.通过使用 errorPlacementhighlightsuccess 函数 API 写入验证配置文件",集成任何自定义反应组件的验证也很简单.

<小时>

感谢任何人到达这条线,这真的是一个很长的话题.这是我的问题:我试图在反应中思考"但无法解决最简单的问题:反应表单验证.

感谢您对我解决此问题的任何提示.

解决方案

我已经构建了一个自定义 Hook 以方便表单验证,也许你会发现它很有用.

Github:https://github.com/bluebill1049/react-hook-form网站:https://react-hook-form.now.sh

下面的快速代码示例

从 'react' 导入 React从'react-hook-form'导入useForm功能应用(){const { register, handleSubmit, errors } = useForm()//初始化钩子const onSubmit = (数据) =>{ console.log(data) }//验证通过时回调返回 (<form onSubmit={handleSubmit(onSubmit)}><input name="firstname" ref={register}/>{/* 注册一个输入 */}<input name="lastname" ref={register({ required: true })}/>{/* 应用所需的验证 */}{errors.lastname &&'姓氏是必需的.'} {/* 错误信息 */}<input name="age" ref={register({ pattern:/\d+/})}/>{/* 应用 Refex 验证 */}{errors.age &&'请输入年龄数字.'} {/* 错误信息 */}<输入类型=提交"/></表单>)}

TL;DR: React provide controlled component, HOC, that is the base idea for React validation library in NPM. However, the weak point is integration with existence Component such as React Select and custom display place of error message

I am migrating from traditional coding jQuery and PHP (used for real and big project for years, not student learn to play code). I focus most of my time on FORM because client's request always about FORM.

Now with FORM, the most important part is validation method/plugin. First forget about some guys tell us about "With React you could easily do controlled component so we do not need validation plugin". Our FORM in production required hundred of Field with many Tabs (for example a personnel form or some crazy organization report), so coding per field is not practical, it s like traditional js coding to validate form.

Come to library, I test and found these three maybe good enough.

  1. React-Validation
  2. React Validation Mixin
  3. Formsy

I will not go into detail about these lib, but the way they work is similar. We must create a component for input, select, textarea and form to make them work. Inside Input component, we define how Input border change class to make border error red and How error message apprear (in div or span below Input).

(There are other validation libs but their method is a json validation for form or even create form with json, that s not my choice because I want to validate form just by a simple attribute in input such as [required, email], not wasting time on ton of definition json)

Now I stuck with this technique in these case:

1. Integration with existence excellent component

I download excelent component from NPM to solve some specific function (like React Select). Now to to the real job, we must validate input for these custom component. This come to an extra work, we must integrate validation to any extra component found. I bang my head to wall to figure out using HOC to validate React Select like this (React-Validation code). And to make this work, I must modify origin HOC to create a custom HOC.

  // Define own Input component 
  function MySelect({ error, isChanged, isUsed, ...selectProps }) {
      return(
         
        <div>
            <Select onChange={selectProps.onChange.bind(this)} {...selectProps} {...( isChanged && isUsed && error ? {
            className: `is-invalid-input ${selectProps.className}`
          } : { className: selectProps.className } )} />
            <input type="hidden"  {...selectProps}  />
          {isChanged && isUsed && error}
        </div>
      ) 
  } 

  const MyValidationSelect = controlSelect(MySelect); //My custom HOC

Now, I cannot think more to work with this technique in future. Imagine we have project and need an extra component. We do not have much time to code our self so download a library. BOOM*, we bang our head to wall to figure out how to make custom component validate. We will waste time on "side project", not the main task (client request feature).

2. Custom place for validation message

Component is good, but it also wrap code inside a layout. Error message must be a part in Input Component. Now come the hard part, some crazy client require to put error message on top of form, or in a modal box. In this case, I still cannot think out a solution if using wrapping Input and error in component.

3. My dirty solution

jQuery appear for long enough for jQuery lib become mature. Validation with jquery could be solve with so called jQuery Validation . Any case we think out for valition could be solved easily and elegant with this lib (custom error placement, custom field, custom validator, custom error format (not just css thing)...)

I just to make jQuery validation with with React form in ComponentDidMount and it work as it is. It is also simple to integrate validation for any custom react component by writing to a "validation config file" with errorPlacement, highlight, success function API.


Thanks for anyone reach this line, this is really a long topic. And here is my question: I tried to "think in react" but cannot solve the simplest thing: React form validation.

Thanks for any hint for me to solve this issue.

解决方案

I have built a custom Hook for easy form validation, maybe you will find it useful.

Github: https://github.com/bluebill1049/react-hook-form website: https://react-hook-form.now.sh

quick code example below

import React from 'react'
import useForm from 'react-hook-form'

function App() {
  const { register, handleSubmit, errors } = useForm() // initialise the hook
  const onSubmit = (data) => { console.log(data) } // callback when validation pass

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}

      <input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
      {errors.lastname && 'Last name is required.'} {/* error message */}

      <input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
      {errors.age && 'Please enter number for age.'} {/* error message */}

      <input type="submit" />
    </form>
  )
}

这篇关于反应和验证库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆