0

remove required validation on input field (if I entered some text in another input field) .I created input fields (two input field )from json .Initially both are required.But if user enter "hello" in first field I want to remove required check from second input field.I used watch and onchange I checked the value of first field .but how to remove required ?I tried by using unregister but still not working

const onChange = e => {
    console.log(e.target.name);
    if (e.target.name == "agencyName") {
      if (agencyName == "hello") {
        //remove required
        unregister({ required: false, name: "contactPerson" });
      }
    }
  };

here is my code https://codesandbox.io/s/react-hook-form-watch-unir2

API link

https://react-hook-form.com/api/

3
  • Can you watch() the field 'contactPerson', then unregister(contactPerson) or unregister(contactPerson.required)? Commented Feb 8, 2020 at 3:47
  • yes I can watch contactPerson but how I will unregistered ? Commented Feb 8, 2020 at 4:05
  • 1
    But what if the user subsequently deletes "hello" from the agency field? You need logic to reinstate required on contact, all too complicated. You need a validation expression that incorporates the value of agency. Commented Feb 8, 2020 at 23:44

1 Answer 1

2

Here's the updated script which makes the Contact Person optional when Agency Name is equal to "hello".

https://codesandbox.io/s/react-hook-form-watch-j396u

Sign up to request clarification or add additional context in comments.

5 Comments

I am getting resone from server..don't change json
please remove this answer
Your question was about making validation optional, which my answer provides, you're now talking about a server issue, which is outside of the scope of your original question.
My question is why you change json ..any other solution
Your code example doesn't have JSON. The fields variable isn't JSON, it's a Javascript array of objects. I had to change value: true to value: isContactPersonRequired because you want the value to be dynamic, not hardcoded to true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.