Lucien Chardon
Lucien Chardon

Reputation: 461

How to validate checkbox group with Vuetify

I have a group of checkboxes in my Vue + Vuetify project. I want to validate that at least one checkbox is checked using Vuetify's "Validation with submit & clear".

Validating a radio group is easy and it works fine by applying a rule to the radio-group:

<v-radio-group v-model="radio" required :rules="radioRules" row>
    <v-radio label="A" value="a"></v-radio>
    <v-radio label="B" value="b"></v-radio>
    <v-radio label="C" value="c"></v-radio>
</v-radio-group>

Problem:

Unfortunately, for checkboxes I can not find a group option like v-checkbox-group, so my checkboxes look like this:

<v-checkbox class="pr-6" v-model="selected" label="A" value="a"></v-checkbox>
<v-checkbox class="pr-6" v-model="selected" label="B" value="b"></v-checkbox>
<v-checkbox class="pr-6" v-model="selected" label="C" value="c"></v-checkbox>

Question:

How can i apply a rule to the checkboxes that validates that at least one checkbox is checked, this.selected.length > 0 ?

Thanks for your help!

Upvotes: 14

Views: 19125

Answers (2)

Ali Bahrami
Ali Bahrami

Reputation: 6073

Why don't you define your selected field of your model an array, and bind it the checkboxes like below?

<v-checkbox class="pr-6" v-model="selected[0]" label="A" value="a"></v-checkbox>
<v-checkbox class="pr-6" v-model="selected[1]" label="B" value="b"></v-checkbox>
<v-checkbox class="pr-6" v-model="selected[2]" label="C" value="c"></v-checkbox>

For validation:

return this.selected.filter(s => s === true).length > 0

Upvotes: 2

Yurii Semeniuk
Yurii Semeniuk

Reputation: 943

It can be done with an array as v-model. Just use computed property for validation:

computed: {
    rules() {
      return [
        this.selected.length > 0 || "At least one item should be selected"
      ];
    }
  }

Here is the Codepen

Also pay attention how hide-details property of v-checkbox is used.

Upvotes: 15

Related Questions