0

I have an input and a checkbox. You can write in the input and submit which will submit correct data. You can disable the input by clicking on the checkbox and it will submit null value which is what I want. But when you fill the input and disable the input with the checkbox and submit, it will submit the current value but I want it to submit null since it is disabled. I'm using react hook form with yup.

Here is an example: https://codesandbox.io/s/zen-snow-rtc9b0?file=/src/App.js

I have tried to use setValue from react hook form(shown in the sandbox) when you check the checkbox it will set the value to null but when you check the checkbox again, the current value will be removed but I want to have the previous value.

4
  • You can also have a state for input, which can be updated using onChange Handler of input... then if you toggle checkbox ... clear the input state. Commented Aug 1, 2022 at 7:12
  • Is there any problem here : const onSubmitHandler = ({ checkbox, number }) => { if (checkbox) { let newData = { checkbox, number: null }; console.log(newData); } else { console.log(checkbox, number); } }; Commented Aug 1, 2022 at 7:16
  • @RKataria Could you please show an example? Commented Aug 1, 2022 at 7:17
  • @AbhishekKamal I also have tried it before. But the issue is that I have multiple inputs based on multiple checkboxes. So this will not be clean. Commented Aug 1, 2022 at 7:18

2 Answers 2

1

You can add additional validation in your transform function to verify if the current value of your checkbox is true. Updated code is here

.transform((value) => Number.isNaN(value) ? null : !isChecked ? value : null )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But what if the yup validation is in another file and there are multiple inputs and checkboxes?
0

It turns out to be a easy. I just added || value to the .trasnform method from yup and it just works!

Here is the working solution: https://codesandbox.io/s/goofy-pasteur-jnkhpm

Explanation: If you take a look at line 12 we use .when for number input to conditionally depend on checkbox. When the checkbox is true, then it accepts null values because of .nullable() and with .transform((value) => (Number.isNaN(value) ? null : value)) it only checks if the value is NaN, if so then make it null else return the number. But now we need to change it to .transform((value) => (Number.isNaN(value) || value ? null : value)) so this means at first place when the checkbox is true(input disabled) and there is value in that input, then return null else return value.

Comments

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.