Search code examples
react-reduxredux-form

How can I do sync field validation based on a param with redux-form?


I need sync field validation on a redux-form field. A param for it (minimum value) is in the redux store.

How can I pass a param to a field validator function? Or even to the form's sync validator func.

As far as I understood I've two options to set field validation:

  1. Pass a validate function to reduxForm()

If i go with this route how can I access the Form props from the validate function? Even if I bind the validate function to the form it can't see the form's props.

App = reduxForm({
  form: "MyForm",
  validate: validate.bind(App)
})(App);

I could not either pass a MyForm.Validate function to the reduxForm.

  1. Set a validate function using the validate prop on Field component

This route i would pass the prop as a parameter to the validation function. Ie. <Field validate={minValue(this.props.minValue)} /> But in this comment it is said is not a good way because it creates a new function on each form render. Indeed it doesn't work properly - no validation until an other field's validation error occurs.

My attempts on codepen


Solution

  • I've found a workaround.

    const Validations = {
      minAmount: minValue => value => {
        return parseFloat(value) < minValue
          ? "Amount must be at least " + minValue
          : undefined;
      }
    };
    

    in component constructor:

    constructor(props) {
        super(props);
        this.minAmount = Validations.minAmount(
            this.props.minAmount
        ); // this a a workaround for validations with parameters causing issues , see https://github.com/erikras/redux-form/issues/2453#issuecomment-272483784
    }
    

    then in Field:

    <Field 
      validate={this.minAmount}
      ....