javascriptvue.jsvuejs2vue-componentvue-select

vue-select "required" attribute not working as expected


I am using Vue-select and want to make the drop-down mandatory, but looks like it is not working.

Tried the required, rules but had no luck.

<v-select label="name"
  :close-on-select="true"
  v-model="CurrentAssignment"
  v-on:input="onSelection"
  :reduce="app => app.id"
  placeholder="Select"
  :options="EligibleOptions" :clearable="false"
  >
</v-select>

Appreciate any inputs.


Solution

  • I assume you are using Vue-select (by looking at the reduce prop and v-select syntax). A validation guide is already available in the documentation. You need to use the required prop in combination with the search-scoped slot.

    Here is a demo in which when submit event will be triggered the selection dropdown will show an error and open automatically.

    Note- I used the form's submit event to trigger the validation. You can use your submission logic.

    Vue.component('v-select', VueSelect.VueSelect)
    
    new Vue({
      el: '#app',
      data: {
        CurrentAssignment: null,
        EligibleOptions: [
          'foo',
          'bar',
          'baz'
        ]
      },
      methods: {
        checkForm() {}
      }
    })
    <script src="https://unpkg.com/vue@2"></script>
    <script src="https://unpkg.com/vue-select@latest"></script>
    <link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css">
    <div id="app">
      <form
        id="app"
        @submit="checkForm"
        action="https://vuejs.org/"
        method="post"
        >
        <v-select label="name"
          :close-on-select="true"
          v-model="CurrentAssignment"
          placeholder="Select"
          :options="EligibleOptions" 
          :clearable="false"
          >
          <template #search="{attributes, events}">
            <input
              class="vs__search"
              :required="!CurrentAssignment"
              v-bind="attributes"
              v-on="events"
              />
          </template>
        </v-select>
        <button type="submit">Submit</button>
      </form>
    </div>