Vuejs - How to submit only the visible elements in a single form (with Vuelidate)

1.2k Views Asked by At

I have a form which includes some hidden and visible elements inside of it and I want to submit some of the elements without validating the hidden ones. At the top of my form there are three radio buttons and they control my form elements. When radiobutton1 selected, some of my form elements become visible and when another radio button is selected, there are some other form elements are visible and some of them are hidden. My question is how am I going to submit my form elements if only they are visible? All of the inputs should be in a single form so I am not allowed to separate them into different forms or different components. What I need to do is when I click the submit button of my form, the form should only submit the visible elements, and it shouldn't send me any error because I left some of the inputs empty (the hidden ones).

I also use Vuedalite so I couldn't figure out how to handle this problem. All of the input fields in the form has the required rule but this rule should be active ONLY IF THEY ARE VISIBLE.

Here is a little code.

<form @submit.prevent="submitForm">
        <!-- Content Section -->
        <div v-show="showContent">
          <!-- Name Field-->
          <div>
            <div>
              <label>Name</label>
              <input v-model="name" :class="{'is-invalid' : $v.networkname2GHz.$error }" type="text"/>
              <small class="errorMessage" v-if="!$v.name.required && $v.name.$dirty">Name field is required.</small>
            </div>
          </div>

          <!-- Surname -->
        <!-- Content Section -->
        <div v-show="showContent">
          <!-- Surname Field-->
          <div>
            <div>
              <label>Surname </label>
              <input v-model="surname" :class="{'is-invalid' : $v.surname.$error }" type="text"/>
              <small class="errorMessage" v-if="!$v.surname.required && $v.surname.$dirty">Surnamefield is required.</small>
            </div>
          </div>
    <div show="showContent">
      <button type="submit">Save</button>
    </div>
</form>

What I want to do is when the user selects the Name radio button only the Name field of the form will be visible and Surname will be hidden, I've done that, no problem. But how do I submit only the name field when surname still empty and has the required rule?

1

There are 1 best solutions below

8
Prime On

You can use v-if instead of v-show. The main difference between the two is that, v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.