Skip to content
Advertisement

Validation in Yup React based on the value of checkbox

I am building a form in React using React-form-hook and validation using yup.

I am using a watch() to check if the checkbox is clicked or not and if it is clicked it will display another input field in the form which was not visible before.

Even when I haven’t clicked the checkbox which means that refer input field is not visible or rendered, it still does not perform the handlesubmit.

I can’t think of a way to get around this.

JavaScript

Validation code in yup.

JavaScript

Reat-hook-form:

JavaScript

If it helps, the complete code is here:

JavaScript

This is what form looks like in the browser.

enter image description here

Advertisement

Answer

This is because the optional field “refer” (as long as “askRefer” is false) is required in your yup schema. You have to add your “askRefer” checkbox to the yup schema and then you can check via the when method, to set validation for “refer” if “askRefer” is true.

JavaScript

Edit React Hook Form - Basic (forked)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement