Use Vuelidate on a v-model with array

1.5k Views Asked by At

I am using vuelidate (https://vuelidate.js.org/) on select option to require and it works when the v-model has a single name $v.selectedWorkflow.$model

<div class="form-group" :class="{ 'form-group--error': $v.selectedWorkflow.$error }">
          <select v-model.trim="$v.selectedWorkflow.$model">
            <option :value="undefined" selected disabled>Select a Workflow</option>
            <option v-for="workflow in workflows"
                :key="workflow.id" :value="workflow">
              {{workflow.name}}
            </option>
          </select>
          </div>

However, when doing v-model with array, I got an error that $error is undefined or sometimes $model is undefined when using $v.usersForRole[role.name].$model I am not sure if I'm doing the right syntax

<div class="form-group" :class="{ 'form-group--error': $v.usersForRole[role.name].$error }">
            <select v-model.trim="$v.usersForRole[role.name].$model">
              <option :value="undefined" selected disabled>Select a User</option>
              <option v-for="user in role.users" :key="user.id" :value="user.id">
                {{user.display_name}}
              </option>
            </select>
          </div>
          <div class="error" v-if="!$v.usersForRole[role.name].required"></div>

here's my validations

validations: {
    title: {
      required,
      minLength: minLength(4)
    },
    slug: {
      required
    },
    selectedWorkflow: {
      required
    },
    usersForRole: {
      required
    }
  },
1

There are 1 best solutions below

1
On BEST ANSWER

Use $each for this requirement.

Ref link: https://vuelidate.js.org/#sub-collections-validation

validations: {
    title: {
      required,
      minLength: minLength(4)
    },
    slug: {
      required
    },
    selectedWorkflow: {
      required
    },
    usersForRole: {
      $each: {
         required
      }
    }
  },