使用反应钩子形式验证字段数组

Abi*_*idh 5 reactjs react-hook-form react-forms

我想向输入字段添加验证。我正在使用反应钩子形式。验证应类似于字段总和应为 100。如果任何字段使总和大于或小于 100,则应在输入字段(最后编辑的字段)处显示错误。

沙箱网址: https://codesandbox.io/s/distracted-elion-z2wob ?file=/src/App.js

谢谢

Dan*_*noz 6

最近,react-hook-form v7.34.0中有一个新功能,可以提供这种开箱即用的验证......

您在定义字段数组时设置它

在您的情况下,您可以在自定义验证函数中运行字段总和 == 100 的检查

useFieldArray({
  name: 'test',
  rules: {
    validate: (fieldArrayValues) => {
      // check that sum of all fields == 100
    },
  }
})
Run Code Online (Sandbox Code Playgroud)

然后你检查/使用错误

errors?.test?.root?.message
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解更多详细信息...

https://react-hook-form.com/api/usefieldarray/

https://github.com/react-hook-form/react-hook-form/issues/6879

https://github.com/react-hook-form/react-hook-form/pull/8562


gui*_*tal 0

你为什么不使用范围?您可以将最小值设置为 0,最大值设置为 100-当前,这将阻止用户设置任何高于 100 的值。关于 100 以下的值,您可以手动检查。


<input type="range" min="0" max={100-currentTotal} step={1}/>
{currentTotal< 100 && lastEdited? "error the sum should be equal to 100" : null}
// I used 1 as the step, but you can set any value


Run Code Online (Sandbox Code Playgroud)