Search code examples
reactjsredux-form

Redux form error is undefined


Why is error undefined with the validate function? I print the errors in the log but is undefined in the Field. When I try to do field.meta.error I get a undefined. I put that in the inputComponent const after the <input>.

const inputComponent = function(field) {
  return (
    <div>
      <input { ...field.input } type={field.type} placeholder={field.placeholder} className={field.className} />
    </div>
  );
}

class Test extends Component {

  render() {

    <div>
       <Field name="name" component={inputComponent} type="email" placeholder="Email" />
       <Field name="password" component={inputComponent} type="password" placeholder="Password" />
    </div>

  }


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

  if(!values.name) {
    errors.categories = "Name error";
  }

  if(!values.password) {
    errors.categories = "Password error";
  }

  return errors;
}

}

Test = reduxForm({
  form: 'NameForm',
  validate
}, null, null)(Test);

export default connect(mapStateToProps, mapDispatchToProps)(Test);

Solution

  • When you return an errors object from validate, the key containing the error messages for a Field must be the same as that field's name prop.

    So in this case:

    function validate(values) {
      const errors = {};
    
      if(!values.name) {
        errors.name = "Name error";
      }
    
      if(!values.password) {
        errors.password = "Password error";
      }
    
      return errors;
    }
    

    For more information, I recommend checking out this validation example from Redux-Form docs.

    Hope this helps!