Home > OS >  validate input based on checkbox
validate input based on checkbox

Time:08-01

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.

CodePudding user response:

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 )

CodePudding user response:

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.

  • Related