Validation form with optional fields react-hook-forms

Stack Overflow Asked by th3g3ntl3man on September 10, 2020

I’m trying to handle a form composed by two parts, one fixed and the other one that gets displayed by a switch.

To handle the forms I’m using react-hook-form.

I defined a validation scheme in the file validation.ts inside the constants folder.
About the optional part I defined a sub-object but it doesn’t work and it gives a compile time error.
Because of this I opted for the solution you’ll find in the link at the bottom of the page

Although I defined the optional input fields inside the validation file, they don’t get recognized when I press the submit button.

How can I fix this problem?

At this link you can find a working example of the problem.

One Answer

The main problem is with your components/Form component, it has this line

// components/Form.tsx
      ?  .... : child;

What you have done here is ignoring all child components without the name prop, where as when rendering the component what you did was rendered them inside <></>, use below alternative instead.

// in App.tsx
{isEnabled ? <Input name="trailerPlate" placeholder="Targa rimorchio" /> : <></>}
{isEnabled ? <Input name="trailerEnrolment" placeholder="Immatricolazione rimorchio" /> : <></>}

Still the validation won't because you need to register the components and your current useEffect code doesn't account for change in number of input fields. Use below code instead

React.useEffect(() => {
  }, [
      Array.isArray(children) ? 
           children.filter(child => : 0

We are using the count of child components with name prop as a trigger for useEffect.

And finally you also have to unregister the fields when you toggle the switch, below is a sample code, feel free to change it according to your preference.

const { handleSubmit, register, setValue, errors, unregister, clearErrors } = useForm<VehicleForm>();

const toggleSwitch = () => {
  if (isEnabled) {
  setIsEnabled(prev => !prev)

Feel free to upvote if I was helpful.

Correct answer by AviKKi on September 10, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP