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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With