简体   繁体   English

React Hook Form:当另一个字段的值为'TEST'时如何根据需要设置一个字段

[英]React Hook Form : how to set a field as required when a value of another field is 'TEST'

I'm looking for a solution for my issue: I have two inputs and I want to make the first one required only when the value of the second input is 'TEST', I'm using React Hook Form with getValues function, this is my code example我正在为我的问题寻找解决方案:我有两个输入,我只想在第二个输入的值为“TEST”时才需要第一个,我正在使用 React Hook Form with getValues function, 这是我的代码示例

Anyone have an idea how to achieve this please?有人知道如何实现这一目标吗? Thank you!谢谢!

  1. As per your implementation, looks like you are trying to make 'LastName' field is required only if the 'FirstName' field contains the value 'test'.根据您的实施,看起来您正试图让“姓氏”字段仅在“名字”字段包含值“测试”时才需要。

  2. Initially it was not working because 'requiredFiedl()' function was not returning true.最初它不起作用,因为“requiredFiedl()”function 没有返回 true。 I modified it as below and now if the 'First Name' the field contains 'test', 'Last Name' will have the required attribute set to 'true'.我如下修改了它,现在如果“名字”字段包含“测试”,“姓氏”将把必需的属性设置为“真”。

    const requiredField = () => { if (watch("firstName") === "test") return true; const requiredField = () => { if (watch("firstName") === "test") 返回真; return false;返回假; }; };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果不需要字段,则 React Hook Form 跳过验证 - React Hook Form Skip validations if a field is not required 如何使用寄存器(react-hook-form)将 useState 字段的值设置为输入字段 - How to set value from useState field to input field with register(react-hook-form) 支持在使用 React Hook 表单验证时更改另一个字段值的回调 - Support callback for changing another field value when using React Hook Form validation 如何使用 react、typescript 和 formik 基于另一个表单字段设置表单字段的值? - How to set the value of form field based on another form field using react, typescript and formik? 使用 react-select 作为必填字段的 React 钩子表单 - React hook form with react-select as required field React-hook-form conditional required validation based on other field - React-hook-form conditional required validation based on other field 如何根据反应中的field1值将field2和field3设置为required - How to set the field2 and field3 to required based on the field1 value in react 使用 react-hook-form 在 React 中编写另一个输入字段时重置一个输入字段 - Reset an input field when another one is written in React with react-hook-form 如何在默认值中为 react-hook-form 设置一个数值以便需要? - How to set a numeric value in defaultValues for react-hook-form in order to be required? React Hook 表单与 Material UI 字段数组有自己的价值 - React Hook Form with Material UI Field Array to Have Their Own Value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM