(注:这篇博客参考自 redux-form 的官方英文文档)左转 http://redux-form.com/6.5.0/examples/syncValidation/
在这篇博客里,我将用 redux-form 实现一个同步验证的表单,它将满足以下条件:
1 有三个输入框:用户名输入框(username),邮箱输入框 (email) 和年龄输入框(age)
2 如果点击输入框获取焦点后未输入内容,则在输入框失去焦点后发出错误(error)提示:XXX 不能为空,且此时不能提交成功
3 如果在输入框中输入内容不合法,比如用户名过长(length>5)发出错误提示:不能大于五个字,且此时不能提交成功
4 如果在输入框中输入内容合法但需警告,则提示警告(warn)内容,此时虽然发出警告但仍能提交成功(请区分和 2 和 3 中的区别)
5 在尚未输入内容时(pristine=true)或在提交过程中 (submitting=true), 禁止使用提交按钮。在点击清空按钮时,调用 reset() 方法清空所有输入框中的内容
首先附上 form.js 的代码:(这份展示一共两份代码:index.js 和 form.js,index.js 的内容请看上一篇博客)
- import React from 'react'import {
- Field,
- reduxForm
- }
- from 'redux-form'const validate = values = >{
- const errors = {}
- if (!values.username) {
- errors.username = '用户名不能为空'
- } else if (values.username.length > 5) {
- errors.username = '不能大于五个字'
- }
- if (!values.email) {
- errors.email = '邮箱不能为空'
- } else if (!/^[A-Z0-9._% -]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
- errors.email = 'Invalid email address'
- }
- if (!values.age) {
- errors.age = '年龄不能为空'
- } else if (isNaN(Number(values.age))) {
- errors.age = '年龄必须是一个数字'
- } else if (Number(values.age) < 18) {
- errors.age = '对不起,你未满18岁'
- }
- return errors
- }
- const warn = values = >{
- const warnings = {}
- if (values.age < 19) {
- warnings.age = '你年龄还有点小哦!'
- }
- return warnings
- }
- const renderField = ({
- input,
- label,
- type,
- meta: {
- touched,
- error,
- warning
- }
- }) = >( < div > <label > {
- label
- } < /label>
- <div>
- <input {...input} placeholder={label} type={type}/ > {
- touched && ((error && <span > {
- error
- } < /span>) || (warning && <span>{warning}</span > ))
- } < /div>
- </div > ) const SyncValidationForm = (props) = >{
- const {
- handleSubmit,
- pristine,
- reset,
- submitting
- } = props
- return ( < form onSubmit = {
- handleSubmit
- } > <Field name = "username"type = "text"component = {
- renderField
- }
- label = "Username" / ><Field name = "email"type = "email"component = {
- renderField
- }
- label = "Email" / ><Field name = "age"type = "number"component = {
- renderField
- }
- label = "Age" / ><div > <button type = "submit"disabled = {
- submitting
- } > Submit < /button>
- <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button > </div>
- </form > )
- }
- export
- default reduxForm({
- form:
- 'syncValidation',
- //你的redux-form的特殊标记,必填项
- validate,
- // 上面定义的一个验证函数,使redux-form同步验证
- warn // 上面定义的一个错误提示函数,使redux-form同步错误提示
- })(SyncValidationForm) //写入的redux-form组件
1 什么是 Field 组件?
Field 组件是 redux-form 组件库中的核心组件,它位于你的输入框(input)或输入框组件的外一层,将其包装起来从而使输入框能和 redux 的 store 直接连接起来。
它有两个最重要的属性:name 属性和 component 属性,且这两个属性都是必填项
- name = "username"type = "text"component = {
- renderField
- }
- label = "Username" / >
在上面的 Field 中 name 和 component 是必填的,而 type 属性和 label 属性是选填的,但选填的属性(如 type 和 label)可通过 props 属性传入它的 component 中,比如以上的 renderField 中
2Field 组件的 name 属性和 component 属性
来源: http://www.cnblogs.com/penghuwan/p/6538987.html