首页 > 解决方案 > 是的,使用 FieldsArray、ReactJS、redux-from 进行验证

问题描述

我使用 yup 验证并尝试构建条件验证对象

通常,我使用 redux 表单中的 Field 来处理表单输入值并使用 yup 对其进行验证,但在另一种情况下,我使用 FieldArray 来实现复杂的条件,这是我使用 FieldArray 的代码:

 <form onSubmit={handleSubmit}>
      <FieldArray
          name="session"
          component={RenderSession}
        />
 </form>

这是我在 FieldsArray 中绑定的组件,

export const RenderSession = ({ fields }) => {return (
  {fields.map((member, index) => (
    <div key={index}>
      <Field
        name={`${member}.name`}
        validate={validateProps}
      />
    </div>
    <Button onClick={() => fields.push({})}>
      Add
    </Button>
  </Row>
</>

我想检查验证字段名称的值 = { $ {member} .startTime} 如何使用 yup 请给我一个解决方案,将 yup 与 FieldsArray 或其他任何东西一起使用。在这种不可能的情况下,教我另辟蹊径,欢迎提问,谢谢

标签: reactjsredux-formyup

解决方案


从 Yup 文档中,您可以根据其架构检查数组的元素,即:

array().of(object().shape({ num: number().max(4) }))

参考:https ://github.com/jquense/yup#arrayoftype-schema-schema

或更合适的例子:

const schema = Yup.object().shape({
  friends: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string()
          .min(4, 'too short')
          .required('Required'), // these constraints take precedence
        salary: Yup.string()
          .min(3, 'cmon')
          .required('Required'), // these constraints take precedence
      })
    )
    .required('Must have friends') // these constraints are shown if and only if inner constraints are satisfied
    .min(3, 'Minimum of 3 friends'),
});

推荐阅读