文本字段的 React-hook-form 条件验证,基于是否选中另一个复选框?
React-hook-form conditional validation of text field, based on if another checkbox is checked?
我正在尝试向文本字段添加验证规则,如果选中表单中的单独复选框,则该字段必须是非空字符串才能提交表单。
这里是 link 目前我所拥有的:https://codesandbox.io/s/magical-hypatia-n7o5w
我需要表单 ("tiger_type") 中的最终文本输入,以便仅在选中 ID 为 'tiger' 的复选框输入时才需要输入值。
我是 React 和 React-hooks-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 的 v5 和 v6 支持 https://react-hook-form.com/api#register
我正在尝试向文本字段添加验证规则,如果选中表单中的单独复选框,则该字段必须是非空字符串才能提交表单。
这里是 link 目前我所拥有的:https://codesandbox.io/s/magical-hypatia-n7o5w
我需要表单 ("tiger_type") 中的最终文本输入,以便仅在选中 ID 为 'tiger' 的复选框输入时才需要输入值。
我是 React 和 React-hooks-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 的 v5 和 v6 支持 https://react-hook-form.com/api#register