2016-10-10 57 views
0

我愿做同步验证,但我不知道怎样来获得字段的对象获取字段的在Redux的形式显示校验错误消息对象

validate.js

const validate = (values) => { 
    const errors = {}; 

    if (!values.firstName) { 
     errors.firstName = 'Firstname is required'; 
    } else if (values.firstName.length < 5 || values.firstName.length > 10) { 
     errors.firstName = 'Firstname must be between 5 - 10'; 
    } 
    return errors; 
} 

export default validate; 

SimpleReduxForm.js

import React, { Component } from 'react' 
import { connect } from 'react-redux' 
import { reduxForm, Field } from 'redux-form' 
import validate from './validate' 

const fields = [ 'firstName', 'lastName', 'age' ] 

@reduxForm({ 
    form: 'simpleReduxForm', 
    fields, 
    validate 
}) 
export default class SimpleReduxForm extends Component { 
    render() { 
     const { handleSubmit, invalid, pristine, submitting } = this.props 
     const { fields } = this.props 
     console.log(fields) 
     return (
      <div> 
       <form onSubmit={ handleSubmit(this.handleFormSubmit) }> 

        <Field name="firstName" component="input" type="text" /> 
        <Field name="lastName" component="input" type="text" /> 
        <Field name="age" component="input" type="number" /> 

        <input type="submit" value="Submit" disabled={ pristine || invalid || submitting }/> 
       </form> 
      </div> 
     ) 
    } 
} 

的输出0从如下

enter image description here

上面的源代码,这是

我看到sample coding从下面的文件只是一个数组不反对,但我不知道怎样找我来工作

const { fields: { firstName, lastName } } = this.props 

... 
{ firstName.touched && firstName.error && <div>{ firstName.error }</div> } 

请指教,谢谢

回答

3

有关如何在redux-forms网站上执行此操作的good example。要点是你应该为你的Field渲染一个组件,然后它可以访问该输入的数据。例如,这里是我的一个使用一些twitter-bootstrap错误样式。

const renderField = ({ input, label, type, meta: { touched, invalid, error } }) => (
    <div class={`form-group ${touched && invalid ? 'has-error' : ''}`}> 
    <label>{label}</label> 
    <input {...input} placeholder={label} type={type} className="form-control" /> 
    <div class="text-danger"> 
     {touched ? error: ''} 
    </div> 
    </div> 
); 

注意,你只需要拉出来touchedinvalid等代替object.property.touched

我用这个从我Field声明如下所示:

<Field name="name" type="text" component={renderField} label="Name" /> 
+0

感谢@Gregg,我忘了提及我可以使用你所建议的编码风格,但我很好奇为什么我不能这样做[例子](https://github.com/erikras/react-redux-universal-hot-例如/斑点/主/ SRC /组件/ SurveyForm/SurveyFor m.js),谢谢 – Artisan

+0

这个例子使用'redux-form @ 3.0.12',最新版本是'6.0.5',这就是为什么。如果你想使用3版主要版本,我想它会起作用。 – Gregg

相关问题