React-hook-form 文本字段的条件验证,基于是否选中另一个复选框?

Sil*_*gns 7 validation reactjs react-hook-form

我正在尝试向文本字段添加验证规则,如果选中表单中的单独复选框,则该字段必须是非空字符串才能提交表单。

这是我到目前为止所拥有的链接:https ://codesandbox.io/s/magical-hypatia-n7o5w

我需要表单(“tiger_type”)中的最终文本输入,仅当选中 id 为“tiger”的复选框输入时才需要输入值。

我是反应和反应钩子形式的新手,所以任何指示将不胜感激。提前致谢。

Ste*_*n J 12

使用提供的回调函数的验证对象react-hook-form。完全工作的解决方案https://codesandbox.io/s/admiring-morning-ljnvk?file=/src/App.js

import { useForm } from 'react-hook-form';
// ... your component implementation 
const { getValues } = useForm(); 

return (
  <form onSubmit={handleSubmit}>
    <input ref={register} name="username" />
    <input
      ref={register({
        validate: {
          required: value => {
            if (!value && getValues('username')) return 'Required when username is provided';
            return true;
          },
        },
      })}
      name="email"
      type="text"
    />
 </form>
);
Run Code Online (Sandbox Code Playgroud)

注意:在撰写本文时,react-hook-form 的 v5 和 v6 支持此解决方案https://react-hook-form.com/api#register