英文:
Why won't validation fire for untouched dynamically added input fields in React Hook Form?
问题
TLDR版本:对于那些熟悉react-hook-form
的人,如何在提交表单时使动态添加的输入字段触发验证?在我的当前用例中,动态添加的字段尚未被触摸,因此在提交表单时不会触发验证。一旦触摸输入字段,验证就会触发。
长版本:所以我有一个在模态框中的表单。这个表单要求添加新成员到一个团队中。有一个[添加成员]按钮,它动态添加了必填的[名字]和[姓氏]输入字段到表单中。在将这些未触摸的字段添加到表单后,当您点击[保存]按钮(提交表单)时,这两个必填字段上的验证不会触发。验证会在它们被触摸后触发。如何在不触摸它们的情况下使这些字段触发验证?
我已经尝试研究这个用例超过一天,但没有找到可以帮助我的东西。
英文:
TLDR version: For those of you that are well versed in react-hook-form
, how do you get dynamically added input fields to fire validation when you submit the form? In my current use case, the dynamically added fields have not been touched, so they won't trigger validation when submitting the form. Once you touch the input fields, the validations trigger.
Long version: So I have a form in a modal. This form asks to add new members to a team. There is a [Add Member] button that dynamically adds REQUIRED [First Name] and [Last Name] input fields to the form. After you add these untouched fields to the form, when you hit the [Save] button, which submits the form, validation on the two REQUIRED fields do not fire. Validation fires after they are touched. How to I get these fields to fire validation without having to touch them?
I have tried to research this use case for over a day now and have not found anything that could help me.
答案1
得分: 1
如何添加成员?
如果您展示给我代码,我认为会更方便。
当以JSX的形式表达时,可以通过附加一个react-hook-form引用来操作它。
function MyForm() {
const { handleSubmit, register, errors } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
{members.map((member) => (
<div>
<input
type="text"
name={`${member.id}-firstName`}
ref={register({ required: true })}
/>
{errors[`${member.id}-firstName`] && <span>此字段为必填项</span>}
<input
type="text"
name={`${member.id}-lastName`}
ref={register({ required: true })}
/>
{errors[`${member.id}-lastName`] && <span>此字段为必填项</span>}
</div>
))}
<button type="submit">提交</button>
</form>
);
}
注意:我已将HTML转义字符替换为原始字符以进行更清晰的显示。
英文:
How do you add members?
I think it would be convenient to help you if you showed me the code.
When expressed in the form of jsx, it can be operated by attaching a react-hook-form ref.
function MyForm() {
const { handleSubmit, register, errors } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
{members.map((memeber) => (
<div>
<input
type=
name={`${member.id}-fisrtName`}
ref={register({ required: true })}
/>
{errors[`${member.id}-fisrtName`] && <span>This field is required</span>}
<input
type="text"
name={`${member.id}-lastName`}
ref={register({ required: true })}
/>
{errors[`${member.id}-lastName`] && <span>This field is required</span>}
</div>
)}
<button type="submit">Submit</button>
</form>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论