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