首页 > 解决方案 > 是的,对具有相同名称的动态表单进行验证

问题描述

我在 React 中有一个表单,我可以动态添加/删除 Min/Max 输入。我正在尝试验证每一行,inputMin应该少于我的inputMax架构。仅当两个输入字段都不为空时才应用验证。react hook formyup

const validationSchema = yup.object().shape({
  inputMin: yup
    .when("inputMax", {
      is: v => v > 0,
      then: number().lessThan(ref("inputMax"), "Min should be less than Max")
  })
});

const { register, triggerValidation } = useForm({ validationSchema });

用户动态添加/删除的 React 组件中的 HTML:

    <input name="inputMin" type="number" ref={register} />
    <input name="inputMax" type="number" ref={register} />

这在只有一行 Max/Min 时有效。但是当有 2 行时,它不能很好地验证。

          MIN     MAX
ROW1 :     0       5
ROW2 :     9       5  <-- (the triggerValidation doesn't catch this error)

我怎样才能告诉它正确地验证每一行inputMin的兄弟姐妹?inputMax

标签: reactjsvalidationyupreact-hook-form

解决方案


推荐阅读