Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Form Field Array Validation

I am using the Redux Form module for all forms in the project. I want to create a validation based on the component props. There is a table with some fields on every row. The table The first field is a dropdown with all the products which come from the store. Every product has an available quantity and if the field quantity is more than the available quantity the Redux Form should return an error for the specific row. I can't do it in the validate function that is passed in the reduxForm method:

reduxForm({
  validate,
  form: 'theNameOfTheForm'
})

The reason why I can't do the table validation in the validate function is because it can't see the current props of the component (I didn't find a way how I can do that). I've decided to pass the validate function as a prop to the FieldArray component:

// some methods

validate(values) {
    // some validation code
}

render() {
    return (
        <FieldArray validate={this.validate} />
    )
}

From the validate method I can access the component props but whatever I return from this method an error is not received by the field prop in the component passed as a component prop to the <FieldArray />.

return 'Some error message';

return ['Some error message'];

return {
    products: 'Some error message'
};

return {
    products: ['Some error message']
};

<FieldArray validate={this.validate} component={FieldArrayComponent} />

const FieldArrayComponent = ({ field, meta }) => {};

How I can do the validation? Am I doing something wrong? Is there another way how I can do the validation?

like image 968
Kiril Stoyanov Avatar asked Jul 01 '17 12:07

Kiril Stoyanov


1 Answers

You can pass the component props to the validate function when using HOC (higher order components) and do the validation in the main validate function (no need to create a method in the component and then pass it to the FieldArray component). Just export the component like this:

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(
  reduxForm({
    validate,
    form: 'ExampleForm'
  })(ExampleForm)
);

The component props are passed in the validation function as a second parameter:

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

  return errors;
};
like image 97
kirpt Avatar answered Sep 21 '22 13:09

kirpt