首页 > 解决方案 > 基于是否选中另一个复选框,对文本字段进行 React-hook-form 条件验证?

问题描述

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

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

我需要形式(“ Tiger_Type”)中的最终文本输入,才需要在选中带有ID'Tiger'的复选框输入时才输入一个值。

我是 react 和 react-hooks-form 的新手,所以任何指针都会受到赞赏。提前致谢。

标签: reactjsvalidationreact-hook-form

解决方案


使用提供的回调函数的验证对象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, 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>
);

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


推荐阅读