Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 521
Lucien Chardon Avatar asked Sep 02 '19 09:09

Lucien Chardon


1 Answers

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.

like image 86
Yurii Semeniuk Avatar answered Sep 29 '22 00:09

Yurii Semeniuk