简体   繁体   中英

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

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. 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; return false; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM