【问题标题】:how to validate formsection in react js using redux form?如何使用redux表单验证react js中的formsection?
【发布时间】:2019-07-12 02:03:06
【问题描述】:

我正在尝试使用 redux 表单库来验证我的表单。我有一个表单部分,其中有两个字段,如firstname(这是必需的)。我想在用户单击按钮时显示错误。

我试过这样 https://codesandbox.io/s/green-frost-414qi

const validateGeneral = general => {
  console.log(general, "general");
  let errors = {};
  // validate address.street etc
  if (general && !general.firstName) {
    errors.firstName = "enter a valid street";
  }
  return errors;
};
const validate = values => {
  console.log(values, "ddd");
  const errors = {};
  errors.general = validateGeneral(values.general);
  return errors;
};

当点击按钮时名字为空时,它应该显示错误消息。

【问题讨论】:

  • 按钮的onClick方法是什么

标签: javascript reactjs redux react-redux redux-form


【解决方案1】:

你应该添加redux-form提供的Field组件的validate prop

在上面的codesandbox例子中,添加如下图的validate prop,就可以正常工作了。

<Field
  name={i.name}
  component={i.component}
  options={i.options || undefined}
  type={i.type}
  validate={i.validate}
/>

【讨论】:

    【解决方案2】:

    您应该包括一个如下验证道具,然后当字段为空并单击按钮时它将显示错误消息

    const required = value =>
      value || typeof value === "number" ? undefined : "Required";
    
     <Field
      name = { i.name }
      component = { i.component }
      options = { i.options || undefined }
      type = { i.type }
      validate = { required }
      />
    

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 2021-05-14
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多