skip to Main Content

I am using react-hook-form in my project, and my form is divided into multiple tabs. Each tab contains different input fields. When the user submits the form, I want to validate all input fields across all tabs.

However, currently, only the input fields in the currently visible tab are being validated.

Is there a way to validate all input fields across all tabs?

I am looking for a way to validate automatically from React-hook-form, I don’t want to validate after I have received the value from the form

Here is the link to my demo: https://codesandbox.io/p/sandbox/d3w7jl

2

Answers


  1. In your given csb url:

     {/* Tab 1 Content */}
          {activeTab === 1 && (
            <ControlledInput
              name="fieldInTab1"
              control={control}
              rules={{ required: "Field in Tab 1 is required" }}
              label="Field in Tab 1"
            />
          )}
    
          {/* Tab 2 Content */}
          {activeTab === 2 && (
            <ControlledInput
              name="fieldInTab2"
              control={control}
              rules={{ required: "Field in Tab 2 is required" }}
              label="Field in Tab 2"
            />
          )}
    

    This is conditional rendering and un-mounting of the component
    instead of un-mounting the component when switching between the tabs, you can try to hide the tab content using css properties like visible Or display.

    Modify the above code to :

          {/* Tab 1 Content */}
           <div className="activeTab === 1 ? show: hide">
            <ControlledInput
              name="fieldInTab1"
              control={control}
              rules={{ required: "Field in Tab 1 is required" }}
              label="Field in Tab 1"
            />
           </div>
    
    
          {/* Tab 2 Content */}
           <div className="activeTab === 2 ? show: hide">
            <ControlledInput
              name="fieldInTab2"
              control={control}
              rules={{ required: "Field in Tab 2 is required" }}
              label="Field in Tab 2"
            />
           </div>
    

    Implement the "hide" and "show" css classes

    Login or Signup to reply.
  2. I believe the following solution could be helpful. I’ve made some modifications to your code, which you can review here: enter link description here.

    Additionally, it’s generally a good practice to split your forms into two independent forms, each with its own validation schema. This approach ensures better scalability and manageability, especially if the number of input fields increases significantly or if the dependencies between tabs become more complex.

    PS: This is a solution to address the issue mentioned in the post, not an enhancement or an explanation of how to improve it further.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search