未捕获的TypeError:使用react和redux-form验证无法读取未定义的属性“length”

时间:2017-05-31 20:08:23

标签: javascript reactjs redux redux-form

我正在使用redux-form并在此做出反应并尝试使用验证。我已经完成了所有工作,但出于某种原因,当我尝试验证字段必须是某个长度属性时,我得到:

Uncaught TypeError: Cannot read property 'length' of undefined

以下是代码:

import React, { Component } from 'react';
import {Field, reduxForm} from 'redux-form';

class PostsNew extends Component {
  constructor(props) {
    super(props);

    this.onSubmit = this.onSubmit.bind(this);
  }

  renderField(field) {
    return (
      <div className="form-group">
        <label><strong>{field.label}:</strong></label>
        <input
          className="form-control"
          type="text"
          {...field.input}
        />
        {field.meta.touched ? field.meta.error : ''}
      </div>
    )
  }

  onSubmit(values) {
    console.log(values);
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit)}>
        <Field
          label="Title for Post"
          name="title"
          component={this.renderField}
        />
        <Field
          label="Categories"
          name="categories"
          component={this.renderField}
        />
        <Field
          label="Post Content"
          name="content"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-success">Submit</button>
      </form>
    );
  }
}

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

  //Validate the inputs from values
  if(!values.title) {
    errors.title = "Enter a title!";
  }
  if(!values.categories) {
    errors.categories = "Enter some categories!";
  }

  if(!values.content) {
    errors.content = "Enter some content please!";
  }

  if(!values.content.length < 20) {
    errors.content = "Content must be longer than 3 characters!";
  }
  //If errors is empty, the form is fine to submit
  //If errors has any properties, redux form assumes form is invalid
  return errors;
}

export default reduxForm({
  validate,
  form: 'PostsNewForm'
})(PostsNew);

3 个答案:

答案 0 :(得分:1)

if(!values.content || !values.content.length < 20){ }

您也可以尝试在属性本身之前检查对象。

答案 1 :(得分:1)

我不确定这是否是正确的方法,但确实有效!

if(values.content){
    if(values.content.length < 20){
      errors.content = "Content must be longer than 20 characters!";
    }
  }

答案 2 :(得分:0)

我觉得最好的方法是进行内联验证

<Field
  label="Post Content"
  name="content"
  component={this.renderField}
  validate={(value) => value && value.length > 20 ? undefined : 'Content must be longer than 20 characters!'}
/>