Search code examples
javascriptreactjsreduxredux-formredux-form-validators

Redux Form Wizard object values validate


In Redux Form, I have issues with getting the error messages to show up properly in a Wizard form with object values. In a for the Wizard first question, I have an object string shown below in code where name = "survey[age]" in WizardFormQuestion1.js file.

The code pen is here for the full code.

WizardFormQuestion1.js

import React from "react";
import { Field, reduxForm } from "redux-form";
import validate from "./validate";

const renderField = ({
  input,
  label,
  survey,
  type,
  meta: { touched, error }
}) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name={input.name} placeholder={label} type={type} />
      {touched && error && <span>{error}</span>}
    </div>
  </div>
);

const WizardFormFirstPage = props => {
  const { handleSubmit } = props;
  return (
    <form onSubmit={handleSubmit}>
      <Field
        name="survey[age]"
        type="text"
        component={renderField}
        label="Age"
      />
      <div>
        <button type="submit" className="next">
          Next
        </button>
      </div>
    </form>
  );
};

export default reduxForm({
  form: "wizard", //                 <------ same form name
  destroyOnUnmount: false, //        <------ preserve form data
  forceUnregisterOnUnmount: true, // <------ unregister fields on unmount
  validate
})(WizardFormFirstPage);

In the validate.js, I tried a few things but haven't been able to validate the object string. The error object I think looks like

error.survey = {'age': 'Required'};

I get JavaScript error message of "age is undefined" or the validation error message doesn't show when I use either dot or bracket notation.

validate.js

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

  values = {
    survey: { age: undefined }
  };


  if (!values.survey["age"]) {
    errors.survey = { age: "Required" };
  }

  return errors;
};

export default validate;

I looked at other references but haven't easily found a valid answer to this problem. Any suggestions? Thank you.


Solution

  • Ok, I solved it by adding empty objects for error and values. It may not be the most elegant, but it works.

    Here's the solution in validate.js.

    const validate = values => {
      const errors = { survey: {} };
      const { survey = {} } = values;
      const { age } = survey;
    
      if (!age) {
        errors.survey.age = "Age is required!";
      }
    
      return errors;
    };
    
    export default validate;