handleSubmit由无效字段触发

时间:2017-12-08 10:20:02

标签: javascript reactjs redux redux-form

所以我使用this示例尝试构建一个同步验证的简单表单。

这是我的表格:

const DatasetForm: React.StatelessComponent = (props: any) => {
    const { handleSubmit, pristine, reset, submitting } = props;
    console.log(props);

    return (<form onSubmit= { handleSubmit }>
            <div>
                <div>
                    <Field
                        name="firstName"
                        component= {renderField}
                        type="text"
                        label="First Name"
                    />
                </div>
                <div>
                    <button type="submit" disabled={submitting}>Submit</button>
                </div>
            </div>
        </form>)
}

我使用完全相同的renderField函数,这是我的验证函数:

const validate = (values: IValues) => {
    let errors: IValues = {
        firstName: ''
    };
    if (!values.firstName) {
        errors.firstName = 'Required';
    }
    else if (values.firstName !== 'aaaaa') {
        errors.firstName = 'Must be aaaaa';
    }
    return errors;
}

handleSubmit函数是一个简单的console.log,并作为道具传递。

现在在示例中,如果字段无效,则似乎不会调用handleSubmit函数。但是在我的代码中,每次单击“提交”按钮时都会调用它。我很长一段时间都盯着我和示例代码而没有发现可能导致这种差异的原因。任何帮助表示赞赏。

编辑:添加导出功能:

export default reduxForm({
    form: 'simpleForm',
    validate
})(DatasetForm);

1 个答案:

答案 0 :(得分:0)

您需要将自定义validate功能传递给自定义表单DatasetForm。像这样:

const validate2 = (values) => {
  let errors = {};
  if (!values.firstName) {
    errors.firstName = 'Required';
  }
  else if (values.firstName !== 'aaaaa') {
    errors.firstName = 'Must be aaaaa';
  }
  console.log(errors);
  return errors;
}
const DatasetForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props;

  return (<form onSubmit={handleSubmit}>
    <div>
      <div>
        <Field
          name="firstName"
          component={renderField}
          type="text"
          label="First Name"
        />
      </div>
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
      </div>
    </div>
  </form>)
}

export default reduxForm({
  form: 'syncValidation',
  validate: validate2,
  warn
})(DatasetForm)

查看此working sample