0

I am using nuxt-vue-select to allow users to select multiple objects form an array locations and then I want to use Vuelidate to try and validate that at least one item in the array has been selected/set on blur however I can not get vuelidate do do this. What am I doing wrong here?

Template

<b-form-group label="Locations" label-for="locations">
    <client-only>
        <v-select
          v-model="userCopy.locations"
          name="locations"
          filterable
          multiple
          placeholder="Select locations"
          label="label"
          :options="locations"
          :class="{ 'is-invalid': v.form.locations.$error }"
          @blur="v.form.locations.$each[index].$touch()"
        />
    </client-only>
</b-form-group>

Script

data() {
    return {
        form:{
            locations: []
        }
    }
},

validations() {
    return {
      form: {
        locations: {
          $each: {
            required
          }
        }
      }
    }
  }

Array data

  { label: 'Avon' },
  { label: 'Bedfordshire' },
  { label: 'Berkshire' },
  { label: 'City of Brighton and Hove' },
  { label: 'City of Bristol' },
Simon
  • 653
  • 3
  • 14
  • 25

2 Answers2

0

For vuelidate you have to use the same filed name as $data, so you need to replace the name form of validations' object to userCopy at first, and apply minLength for your locations length:

validations() {
    return {
      userCopy: { // change this
        locations: {
          // ... to try and validate that at least one item in the array
          // use minLength to do that
          minLength: minLength(1)
          $each: {
            required
          }
        }
      }
    }
  }

To deal with array structure, I recommend to try form-validation.js.

Ernest
  • 174
  • 7
  • If the user focuses on the input. then navigates away, the error on blur is not registered – Simon Jul 13 '20 at 08:23
0

According to Vuelidate document(https://vuelidate-next.netlify.app/validators.html#required),

you should use required to check if the array is empty rather than minLength

Therefore your code should be like:

validations() {
  return {
    form: {
      locations: {
        required,
        $each: { ... //validation for each item }
      }
    }
  }
}

Hope this answer your question.

theedchen
  • 1,564
  • 4
  • 10
  • 17