HDykins
HDykins

Reputation: 11

How to change redux-form shouldValidate option based on changing state

I'm currently using redux-form and only want the validation to be run based on the button that is being pressed, after dispatching the redux-form submit action. At the moment I change the state when the button is clicked by dispatching my own action and using nextProps of the shouldValidate() function to return true or false depending on the value in the state.

BriefForm = reduxForm({
  form: "brief", // a unique name for this form
  destroyOnUnmount: false,
  forceUnregisterOnUnmount: false,
  enableReinitialize: true,
  keepDirtyOnReinitialize: false,
  shouldValidate(params) {
    if (params.nextProps && params.nextProps.submitButton === "save") {
      return false
    } else {
      return true
    }
  },
  validate
})(BriefForm);

However, even when params.nextProps.submitButton === "save" resolves to true and the shouldValidate function returns false, the validation function for the form still runs. I want the form to submit but not validate when clicking the "save" button, but at other times to submit and validate, but it seems like it cant be dynamic?

Upvotes: 1

Views: 1697

Answers (1)

blaz
blaz

Reputation: 4068

Have you tried to use connect from 'react-redux' to pass shouldValidate to reduxForm()? Something like this:

const mapStateToProps = state => ({
  shouldValidate: ({ nextProps: getNextProps(state) }) => {
      return nextProps && nextProps.submitButton === "save"
    }
})

BriefForm = connect(
  mapStateToProps
)(reduxForm({
  form: "brief", // a unique name for this form
  destroyOnUnmount: false,
  forceUnregisterOnUnmount: false,
  enableReinitialize: true,
  keepDirtyOnReinitialize: false,
  validate
})(BriefForm));

Upvotes: 1

Related Questions