redux-forms 在提交前进行预验证

redux-forms pre validate before submission

我想在提交前验证表单并在底部显示一个常见错误,而不是将错误附加到特定字段。 errros.fieldname="Age > 10"。 没有错误会提示继续提交,确认后会调用form-submit.

使用 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>
                    }

问题是值未在 BeforeValidate 函数中定义。 redux-form 中提供的 synch validate 没有提供设置常见错误信息的方法。不确定异步验证是正确的地方。 所以我被抓住了。请帮忙。

您可以使用正常的 validate 函数并添加 _error。整个表单而不是字段会出错。

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

在您的表单中 render 使用 this.props.error 检查表单错误。 像这样:

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