开发者问题收集

未捕获的类型错误:无法读取未定义的属性“长度”,使用 react 和 redux-form 验证

2017-05-31
11127

我在这里使用 redux-form 和 react,并尝试使用验证。我已使其全部运行,但由于某种原因,当我尝试验证字段必须具有一定长度的属性时,我得到了:

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个回答
if(!values.content || !values.content.length < 20){ }

您也可以尝试先检查对象,然后再检查属性本身。

Giorgi Khorguani
2017-05-31

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

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

我认为最好的方法是进行内联验证

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