Search code examples
reactjsreact-redux-form

redux-forms pre validate before submission


I would like to validate the form before submission and display a common error in the bottom, instead of attaching error to a particular field. errros.fieldname="Age > 10". Upon no errors, will prompt a message to continue submission and then upon confirmation will call form-submit.

What is the correct approach to do using redux-forms?

 BeforeValidate(values)
  {
    if (<<some validation condition>>) {
        this.setState({err:"Error"})
        return;
    } else 
    {
        this.setState({DialogOpen:true, err:""})
    } 
  }

To display the common error message instead of attaching as error.text somewhere in render function

&nbsp;{ this.state.err !='' &&  
                            <span className="text text-danger"><strong>No Value selected!
</strong></span>
                    }

The problem is values is not defined in BeforeValidate function. The synch validate provided in redux-form does not provide a way to set the common error message. Not sure asynch-validate is the correct place. So I am caught. Please help.


Solution

  • You can use normal validate function and add _error. It will be error for whole form not a field.

    const validate = ({ options }) => {
      const errors = {};
      if (options.length === 0) errors._error = 'required';
      return errors;
    };
    

    In your form render use this.props.error to check for form error. Something like this:

      render() {
        const { handleSubmit, onSubmit, submitting, error, submitFailed } = this.props;
        return (
          <View>
            {error &&
              <FormValidationMessage>
                {I18n.t(error)}
              </FormValidationMessage>}
          </View>
        );
      }